<?php

namespace App\Http\Controllers;

use Aws\Ses\SesClient;
use App\Http\Controllers\Base\CommunityPannelBaseController;
use App\Http\Controllers\Traits\LazyLoadsRepositories;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Shuchkin\SimpleXLSX;
use Stripe;
use Illuminate\Support\Str;

class CommunityPannelController extends CommunityPannelBaseController
{
    use LazyLoadsRepositories;

    public function __construct(Filesystem $filesystem)
    {
        parent::__construct();
        $this->file = $filesystem;
        // if (!($this->community->isOwner())) redirect('home')->send();

        // if (!($this->community->present()->canManage())) redirect('home')->send();

        if (! isset($this->community) || ! $this->community->present()->hasCardAdded()) {
            // redirect('home')->send();
            return redirect(config('app.url'))->send();
        }
    }

    public function panneldashboard(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        return $this->render('community.pannel.index', [
            'title' => $this->setTitle(trans('community.pannel.manage-community')),
        ]);
    }

    public function pannelsetting(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {

            $validator = \Validator::make($val, [
                'title' => 'required',
            ]);

            if (! $validator->fails()) {
                $save = $this->communityRepository()->saveExternal($val, $this->community);
                if ($save) {
                    \Session::flash('success', trans('organizationsettings.information-updated-successfully'));

                    $isCompleted = $this->communityRepository()->checkFieldsComplete($this->community->id);
                    if ($isCompleted == 0) {
                        return redirect($this->community->present()->url('pannelsetting'));
                    } else {
                        return redirect($this->community->present()->url('pannelsetting'));
                    }
                    // $message = 'Information updated successfully.';

                } else {
                    $message = trans('organizationsettings.invalid-information');
                }
            } else {
                $message = $validator->messages()->first();
            }
        }

        return $this->render('community.pannel.pannel-settings', ['fields' => $this->customFieldRepository()->listAll('community'), 'message' => $message], [
            'title' => $this->setTitle(trans('global.edit')),
        ]);
    }
	
	public function logoSetting(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')){

			$save = $this->communityRepository()->saveExternalLogos($val, $this->community);
			if ($save) {
                \Session::flash('success', trans('organizationsettings.settings-updated-successfully'));

				$isCompleted = $this->communityRepository()->checkFieldsComplete($this->community->id);
				if ($isCompleted == 0) {
					return redirect($this->community->present()->url('logosetting'));
				} else {
					return redirect($this->community->present()->url('logosetting'));
				}
				// $message = 'Information updated successfully.';

			} else {
                $message = trans('organizationsettings.invalid-information');
			}           
        }

        return $this->render('community.pannel.logo-settings', ['message' => $message], [
            'title' => $this->setTitle(trans('global.edit')),
        ]);
    }
	
	public function domainUrlSetting(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {

            $validator = \Validator::make($val, [
                'domain_name' => 'required',
            ]);

            if (! $validator->fails()) {
                $save = $this->communityRepository()->saveExternalDomain($val, $this->community);
                if ($save) {
                    \Session::flash('success', 'Domain information saved successfully.');
					 return redirect($this->community->present()->url('domainurlsetting'));
                } else {
                    $message = 'Other community already using this domain.';
                }
            } else {
                $message = $validator->messages()->first();
            }
        }

        return $this->render('community.pannel.domain-url-settings', ['message' => $message], [
            'title' => $this->setTitle(trans('global.edit')),
        ]);
    }

    public function pannelmembers(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        return $this->render('community.pannel.members', ['members' => $this->communityMemberRepository()->listUsers($this->community->id)], ['title' => $this->setTitle('Members')]);
    }

    public function panneldesign(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {
            $this->userRepository()->saveDesign($val);
            $message = trans('community.design-save');
        }

        return $this->render('community.pannel.designcommunity', ['user' => $this->community->user, 'message' => $message], [
            'title' => $this->setTitle(trans('community.design')),
        ]);
    }

    public function topbanner(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $page = 'homecms';
        $cms = 'topbanner';

        $advertises = $this->communityTopbannerRepository()->getByCommunityId($this->community->id);

        $this->theme->share('settingPage', 'homecms');

        return $this->render('community.pannel.cms.topbanner', ['settingPage' => $page, 'cms' => $cms, 'advertises' => $advertises], [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function addtopbanner(Request $request)
    {

        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');

        $message = '';
        if ($val = $request->get('val')) {
            $this->communityTopbannerRepository()->addAdvertise($val);
            $message = 'Advertisement saved successfully';
        }

        return $this->render('community.pannel.cms.addtopbanner', ['message' => $message], [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function gallery(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');

        return $this->render('community.pannel.cms.gallery', [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function homepagecontents(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');

        $pagetype = $request->get('pagetype');
        $save_type = $request->get('save_type');

        if ($request->isMethod('post') && $request->get('save_homepage_id')) {
            $homepage_id = (int) $request->get('homepage_id', 0);

            if ($homepage_id !== 0) {
                $page = $this->communityPagesRepository()->getByIdComId($homepage_id, $this->community->id);

                if (! $page || (int) $page->status !== 1 || (int) $page->is_menu !== 0) {
                    \Session::flash('error', 'Invalid page selection');

                    return redirect()->back();
                }
            }

            $this->communityHomeContentsRepository()->updateHomepageId($this->community->id, \Auth::user()->id, $homepage_id);
            \Session::flash('success', trans('cms.setting-saved-successfully'));

            return redirect()->back();
        }

        if ($val = $request->get('val')) {

            $pagehtml = $request->get('pagehtml');

            $addContents = $this->communityHomeContentsRepository()->addContents($val, $this->community->id, \Auth::user()->id, $pagehtml, $save_type);

            if ($addContents) {
                $this->communityTopbannerRepository()->addAdvertise($val, $this->community->id);
            }

            $addMapContactShow = $this->communityRepository()->addMapContactShow($val, $this->community->id);

            // return redirect($this->community->present()->url('homepagecontents'));
        }

        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

        if (! $contents) {
            $arrVal = ['hometheme' => 3];
            $contents = $this->communityHomeContentsRepository()->addContents($arrVal, $this->community->id, $this->community->user_id);
        }

        $theme_id = $request->get('use_theme_id');
        $selected_theme = '';
        if ($theme_id) {
            $selected_theme = $this->themesRepository()->getById($theme_id);
        }

        $advertises = $this->communityTopbannerRepository()->getByCommunityId($this->community->id);

        $published_pages = $this->communityPagesRepository()->getAllPublishedPagesByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.homepagecontents', ['contents' => $contents, 'advertises' => $advertises, 'pagetype' => $pagetype, 'selected_theme' => $selected_theme, 'theme_id' => $theme_id, 'published_pages' => $published_pages], [
            'title' => $this->setTitle(trans('cms.home-cms')),
        ]);
    }

    public function resaveHomepageTheme9(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        /*if (! $request->isMethod('post')) {
            return redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));
        }*/

        $this->communityHomeContentsRepository()->updateThemeOnly($this->community->id, \Auth::user()->id, 9);
        //\Session::flash('success', trans('cms.file-contents-saved-successfully'));

        return redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));
    }
	
	public function saveFolderTheme(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->communityHomeContentsRepository()->updateThemeOnly($this->community->id, \Auth::user()->id, 7);
        //\Session::flash('success', trans('cms.file-contents-saved-successfully'));

        //return redirect($this->community->present()->url('managethemefiles'));
		
		$templatePublicDir = public_path('themes/idh/default/views/templates/'.$this->community->id);
		
        if (! is_dir($templatePublicDir)) {
            $this->file->makeDirectory($templatePublicDir, 0777, true, true);
        }
		
		 return redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));
    }

    public function saveHomePageIndex(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $index_html = $request->get('index_html');
        if ($index_html) {

            file_put_contents('themes/idh/default/views/templates/'.$community->id.'/index.html', $index_html);
            \Session::flash('success', trans('cms.file-contents-saved-successfully'));

            return redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));
        }

        return redirect($this->community->present()->url());
    }

    public function manageThemeFiles(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $templatePublicDir = public_path('themes/idh/default/views/templates/'.$community->id);
        if (! is_dir($templatePublicDir)) {
            $this->file->makeDirectory($templatePublicDir, 0777, true, true);
        }
		
		return  redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));

        return $this->render('community.pannel.cms.thememanage.lists', ['community' => $community, 'checking_path' => str_replace('\\', '/', $templatePublicDir)], [
            'title' => $this->setTitle(trans('cms.manage-template-files')),
        ]);
    }

    public function manageAiWebsitePages(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        // AI Website Builder deployed/generated pages are stored in /public/c/{id}/web
        // Use an absolute path so file_exists()/scandir() work regardless of CWD.
        $checking_path = str_replace('\\', '/', public_path('c/'.$community->id.'/web'));

        return redirect($this->community->present()->url('homepagecontents?pagetype=page-design'));
		 
        return $this->render('community.pannel.cms.thememanage.aiwb-pages', [
            'community' => $community,
            'checking_path' => $checking_path,
            'show_manage_actions' => true,
        ], [
            'title' => $this->setTitle(trans('cms.aiwb-theme-files')),
        ]);
    }

    public function uploadThemeMedia(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'thememediaupload');
        $community = $this->community;

        if ($request->ajax() || (int) $request->get('ajax') === 1) {
            return view('themes.frontend.default.views.community.pannel.cms.thememanage.upload-media', [
                'community' => $community,
            ]);
        }

        return $this->render('community.pannel.cms.thememanage.upload-media', ['community' => $community], [
            'title' => $this->setTitle('Theme Media Upload'),
        ]);
    }

    public function themeMediaFiles(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'thememediafiles');
        $community = $this->community;
        $term = $request->get('term');
        $type = $request->get('type');

        $documents = $this->communityDocumentsRepository()->getThemeDocuments($this->community->id, 0, 10, $term, $type);

        $folder_path = 'themes/idh/default/views/templates/'.$community->id;
        $file_types = ['png', 'jpg', 'jpeg', 'gif', 'mp4'];
        $default_media_files = $this->list_files($folder_path, $file_types);

        // return $default_media_files;

        if (($request->ajax() || (int) $request->get('ajax') === 1) && (int) $request->get('inline_bundle') === 1) {
            return view('themes.frontend.default.views.community.pannel.cms.thememanage.media-inline', [
                'community' => $community,
                'documents' => $documents,
                'type' => $type,
                'default_media_files' => $default_media_files,
            ]);
        }

        if ($request->ajax() || (int) $request->get('ajax') === 1) {
            return view('themes.frontend.default.views.community.pannel.cms.thememanage.media-files', [
                'community' => $community,
                'documents' => $documents,
                'type' => $type,
                'default_media_files' => $default_media_files,
            ]);
        }

        return $this->render('community.pannel.cms.thememanage.media-files', ['community' => $community, 'documents' => $documents,
            'type' => $type, 'default_media_files' => $default_media_files], [
                'title' => $this->setTitle(trans('cms.media-files')),
            ]);
    }

    public function list_files($path, $file_types)
    {
        try {
            $resolvedPath = $path;
            if (!is_dir($resolvedPath)) {
                $publicCandidate = public_path($path);
                if (is_dir($publicCandidate)) {
                    $resolvedPath = $publicCandidate;
                } else {
                    return [];
                }
            }

            $directory = new \RecursiveDirectoryIterator($resolvedPath, \FilesystemIterator::SKIP_DOTS);
            $iterator = new \RecursiveIteratorIterator($directory);
            $files = [];
            $publicRoot = rtrim(str_replace('\\', '/', public_path()), '/');

            foreach ($iterator as $info) {
                if (!$info || !$info->isFile()) {
                    continue;
                }
                $ext = strtolower((string) $info->getExtension());
                if (!in_array($ext, $file_types, true)) {
                    continue;
                }

                $file_path = str_replace('\\', '/', (string) $info->getPathname());
                if ($publicRoot && strpos($file_path, $publicRoot.'/') === 0) {
                    $files[] = substr($file_path, strlen($publicRoot) + 1);
                } else {
                    $files[] = $file_path;
                }
            }

            return $files;
        } catch (\Throwable $e) {
            return [];
        }
    }

    public function themeMediaDelete(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'thememediafiles');
        $community = $this->community;

        $id = $request->get('id');
        $this->communityDocumentsRepository()->deleteMediaDocument($community->id, $id);
    }

    public function uploadingThemeMedia(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $user = (empty($user)) ? \Auth::user() : $user;
        $CDNRepository = $this->cDNRepository();

        $document_description = $request->get('document_description');

        if ($request->hasFile('documents')) {

            $mainFile = $request->file('documents');
            $fileExt = $mainFile->getClientOriginalExtension();
            $document_size = $mainFile->getSize();

            if (checkAvailableSpace($this->community->id, $document_size) == 0) {
                return 2;
            }

            $userid = \Auth::user()->id;
            $filePath = 'uploads/community/'.$this->community->id.'/';

            // ensure the folder exists

            $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
            $fileName = md5($mainFile->getClientOriginalName().time()).'.'.$fileExt;
            $file_path = $filePath.$fileName;
            $document_original_name = $mainFile->getClientOriginalName();

            $mainFile->move(public_path().'/'.$filePath, $fileName);
            if (in_array(strtolower($fileExt), ['webm', 'ogv', 'ogg', 'mov', 'avi', 'mp4'])) {
                $uploadPath = 'media/appvideo/'.$this->community->id.'/'.$fileName;
                $newFileName = $CDNRepository->upload(public_path().'/'.$file_path, $uploadPath, 'videoUpload');
            } else {
                $newFileName = $CDNRepository->upload(public_path().'/'.$file_path, $file_path);
            }

            $CDNRepository->deleteThisFile(public_path().'/'.$file_path);

            $file_path = $newFileName;

            if ($file_path) {
                $document = $this->communityDocumentsRepository()->saveThemeDocument($user->id, $this->community->id, 0, $fileExt, $file_path, $document_size, $document_original_name, $document_description);

                if ($document) {
                    $fileArray = [
                        'community_id' => $this->community->id,
                        'user_id' => \Auth::user()->id,
                        'file_path' => $file_path,
                        'file_name' => $document_original_name,
                        'file_type' => $fileExt,
                        'file_size' => $document_size,
                        'uploaded_date' => date('Y-m-d'),
                        'type' => 'theme-file',
                        'type_id' => $this->community->id,
                        'sub_type_id' => $this->community->id,
                        'upload_key' => Str::random(20),
                    ];
                    $this->communitySpaceUsedRepository()->save($fileArray);
                }

                return 1;
            }
        }
    }

    public function manageThemeFolderFiles(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $path_url = $request->get('path_url');
        $folder_name = $request->get('folder_name');

        $allow_delete = true;
        $show_manage_actions = false;
        $allowed_extensions = 'html,css,js';
        $aiwbRoot = realpath(public_path('c/'.$community->id.'/web'));
        $templateRoot = realpath(public_path('themes/idh/default/views/templates/'.$community->id));
        if (! $templateRoot) {
            $templateRoot = realpath(base_path('themes/idh/default/views/templates/'.$community->id));
        }
        $targetPath = $path_url ? realpath($path_url) : null;
        if ($aiwbRoot && $targetPath) {
            $aiwbRoot = rtrim($aiwbRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
            $targetPath = rtrim($targetPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
            if (str_starts_with($targetPath, $aiwbRoot)) {
                $allow_delete = true;
                $show_manage_actions = true;
                $allowed_extensions = 'html,js,css';
				$html_type='web';
            }
        }

        if ($templateRoot && $targetPath) {
            $templateRoot = rtrim($templateRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
            if (str_starts_with($targetPath, $templateRoot)) {
                $show_manage_actions = true;
                $allowed_extensions = 'html,css,js';
				$html_type='stat';
            }
        }

        $default_folder_path = 'themes/idh/default/views/templates/'.$community->id.'/';

        $folder_short_path = explode($default_folder_path, $path_url);
		
        $folder_short_path_name = '';
        if (isset($folder_short_path[1])) {
            $folder_short_path_name = $folder_short_path[1];
        }

        return (string) $this->theme->section('community.pannel.cms.thememanage.all-files', ['checking_path' => $path_url, 'folder_name' => $folder_name, 'folder_short_path_name' => $folder_short_path_name, 'allow_delete' => $allow_delete, 'show_manage_actions' => $show_manage_actions, 'allowed_extensions' => $allowed_extensions,'html_type'=>$html_type]);
    }

    public function themeFileToEdit(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $path_url = $request->get('path_url');
        $name = $request->get('name');

        return (string) $this->theme->section('community.pannel.cms.thememanage.file-to-edit', ['checking_path' => $path_url, 'name' => $name]);
    }
	
	public function themeFileEditorPage(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $checking_path = (string) $request->get('path_url', '');
		$checking_path=base64_decode($checking_path);
		
		$relative_path = (string) $request->get('rlp', '');
		$relative_path=base64_decode($relative_path);
		
        $name = (string) $request->get('name', '');

        if ($name === '' && $checking_path !== '') {
            $name = basename($checking_path);
        }

        return $this->render('community.pannel.cms.thememanage.file-editor', [
            'community' => $community,
            'path' => $checking_path,
            'name' => $name,
			'relative_path'=>$relative_path,
        ], [
            'title' => $this->setTitle(($name !== '' ? $name : 'Theme File').' Editor'),
        ]);
    }

    public function themeFileToSave(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $getfile_html = $request->get('getfile_html');
        $path_url = $request->get('path_url');
		$relativePath=(string) $request->input('rlp', '');
		
        if ($path_url) {
            file_put_contents($path_url, $getfile_html);
            $this->cleanupThemeFileAiArtifactsForPath((int) $community->id, (string) $path_url);
			
			$data=$this->filesManageRepository()->getByPath((int) $community->id,$relativePath);
			if($data){
			     $data->delete();
			}
        }
        // return redirect($this->community->present()->url());
    }

    public function themeFileCreate(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $currentPath = (string) $request->get('current_path', '');
        $rawFileName = trim((string) $request->get('file_name', ''));
        $selectedExt = strtolower(trim((string) $request->get('file_ext', '')));
        $pageTitle = trim((string) $request->get('page_title', ''));
        $addHeader = (int) $request->get('add_header', 0) === 1;
        $addFooter = (int) $request->get('add_footer', 0) === 1;

        $allowedDir = $this->resolveAiwbDirectoryPath((int) $community->id, $currentPath);
        if (! $allowedDir) {
            return response()->json(['error' => 'Invalid target directory'], 422);
        }

        if ($rawFileName === '') {
            return response()->json(['error' => 'File name is required'], 422);
        }

        // Backward compatibility: allow extension in file_name when file_ext is not provided.
        if ($selectedExt === '' && str_contains($rawFileName, '.')) {
            $selectedExt = strtolower((string) pathinfo($rawFileName, PATHINFO_EXTENSION));
            $rawFileName = (string) pathinfo($rawFileName, PATHINFO_FILENAME);
        }

        $allowedExt = $this->getAllowedExtensionsForDirectory((int) $community->id, $allowedDir);
        if (! in_array($selectedExt, $allowedExt, true)) {
            return response()->json(['error' => 'Please select a valid extension ('.implode(', ', $allowedExt).')'], 422);
        }

        if (! preg_match('/^[A-Za-z0-9_\-]+$/', $rawFileName)) {
            return response()->json(['error' => 'Invalid file name'], 422);
        }

        if (str_contains($rawFileName, '..') || str_contains($rawFileName, '/') || str_contains($rawFileName, '\\')) {
            return response()->json(['error' => 'Invalid file name'], 422);
        }

        $fileName = $rawFileName.'.'.$selectedExt;
        $ext = $selectedExt;

        if ($ext !== 'php') {
            $addHeader = false;
            $addFooter = false;
        }

        $newPath = str_replace('\\', '/', rtrim($allowedDir, '/').'/'.$fileName);
        if (file_exists($newPath)) {
            return response()->json(['error' => 'File already exists'], 422);
        }

        $content = $this->buildNewThemeFileContent($ext, $fileName, $allowedDir, $addHeader, $addFooter, $pageTitle);
        if (@file_put_contents($newPath, $content) === false) {
            return response()->json(['error' => 'Failed to create file'], 500);
        }
		
		$relativePath =  preg_replace('#^.*?/public/#', 'public/', str_replace('\\', '/', $newPath));

        $redirectUrl = $community->present()->url('themefileeditorpage').'?path_url='.urlencode(base64_encode($newPath)).'&name='.urlencode($fileName).'&rlp='.urlencode(base64_encode($relativePath));

        return response()->json([
            'success' => true,
            'path' => $newPath,
            'name' => $fileName,
            'redirect_url' => $redirectUrl,
        ]);
    }

    public function themeFileUpload(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $templatePublicDir = public_path('themes/idh/default/views/templates/'.$community->id);
        if (! is_dir($templatePublicDir)) {
            $this->file->makeDirectory($templatePublicDir, 0777, true, true);
        }

        $currentPath = (string) $request->get('current_path', '');
        $allowedDir = $this->resolveAiwbDirectoryPath((int) $community->id, $currentPath);
        if (! $allowedDir) {
            return response()->json(['error' => 'Invalid target directory'], 422);
        }

        $allowedExt = $this->getAllowedExtensionsForDirectory((int) $community->id, $allowedDir);

        $uploads = [];
        if ($request->hasFile('upload_files')) {
            $multi = $request->file('upload_files');
            if (is_array($multi)) {
                $uploads = $multi;
            } elseif ($multi) {
                $uploads = [$multi];
            }
        }

        $legacySingleUpload = false;
        if (empty($uploads) && $request->hasFile('upload_file')) {
            $single = $request->file('upload_file');
            if ($single) {
                $uploads = [$single];
                $legacySingleUpload = true;
            }
        }

        if (empty($uploads)) {
            return response()->json(['error' => 'Please select a file to upload'], 422);
        }

        $preparedUploads = [];
        foreach ($uploads as $upload) {
            if (! $upload || ! $upload->isValid()) {
                return response()->json(['error' => 'One or more files are invalid.'], 422);
            }

            $origName = trim((string) $upload->getClientOriginalName());
            if ($origName === '') {
                return response()->json(['error' => 'One or more files have invalid names.'], 422);
            }

            $safeName = preg_replace('/[^A-Za-z0-9._\-]/', '_', $origName) ?? $origName;
            if ($safeName === '' || str_contains($safeName, '..') || str_contains($safeName, '/') || str_contains($safeName, '\\')) {
                return response()->json(['error' => 'One or more files have invalid names.'], 422);
            }

            $ext = strtolower((string) pathinfo($safeName, PATHINFO_EXTENSION));
            if (! in_array($ext, $allowedExt, true)) {
                return response()->json(['error' => 'Unsupported file extension. Allowed: '.implode(', ', $allowedExt)], 422);
            }

            $preparedUploads[] = [
                'file' => $upload,
                'safe_name' => $safeName,
                'ext' => $ext,
            ];
        }

        $uploadedFiles = [];
        foreach ($preparedUploads as $entry) {
            $upload = $entry['file'];
            $safeName = (string) $entry['safe_name'];
            $ext = (string) $entry['ext'];

            $targetPath = str_replace('\\', '/', rtrim($allowedDir, '/').'/'.$safeName);
            if (file_exists($targetPath)) {
                $base = (string) pathinfo($safeName, PATHINFO_FILENAME);
                $suffix = $ext !== '' ? '.'.$ext : '';
                for ($i = 1; $i <= 999; $i++) {
                    $candidate = str_replace('\\', '/', rtrim($allowedDir, '/').'/'.$base.'-'.$i.$suffix);
                    if (! file_exists($candidate)) {
                        $targetPath = $candidate;
                        $safeName = basename($candidate);
                        break;
                    }
                }
            }

            if (! @move_uploaded_file($upload->getPathname(), $targetPath)) {
                return response()->json(['error' => 'Failed to upload file: '.$safeName], 500);
            }

            $uploadedFiles[] = [
                'path' => $targetPath,
                'name' => $safeName,
            ];
        }

        if ($legacySingleUpload && count($uploadedFiles) === 1) {
            $single = $uploadedFiles[0];
            $redirectUrl = $community->present()->url('themefileeditorpage').'?path_url='.urlencode(base64_encode($single['path'])).'&name='.urlencode($single['name']);

            return response()->json([
                'success' => true,
                'path' => $single['path'],
                'name' => $single['name'],
                'redirect_url' => $redirectUrl,
            ]);
        }

        return response()->json([
            'success' => true,
            'uploaded_count' => count($uploadedFiles),
            'uploaded_files' => $uploadedFiles,
        ]);
    }

    private function resolveAiwbDirectoryPath(int $communityId, string $currentPath): ?string
    {
        $roots = [];

        $aiwbRoot = realpath(public_path('c/'.$communityId.'/web'));
        if ($aiwbRoot && is_dir($aiwbRoot)) {
            $roots[] = str_replace('\\', '/', $aiwbRoot);
        }

        $templateRootPublic = realpath(public_path('themes/idh/default/views/templates/'.$communityId));
        if ($templateRootPublic && is_dir($templateRootPublic)) {
            $roots[] = str_replace('\\', '/', $templateRootPublic);
        }

        // Backward compatibility for environments that keep this outside public/.
        $templateRootBase = realpath(base_path('themes/idh/default/views/templates/'.$communityId));
        if ($templateRootBase && is_dir($templateRootBase)) {
            $roots[] = str_replace('\\', '/', $templateRootBase);
        }

        if (empty($roots)) {
            return null;
        }

        $target = trim($currentPath);
        if ($target === '') {
            return $roots[0];
        }

        $targetNormInput = str_replace('\\', '/', $target);
        $targetNormInput = trim($targetNormInput);

        $candidatePaths = [];

        $targetReal = realpath($targetNormInput);
        if ($targetReal && is_dir($targetReal)) {
            $candidatePaths[] = str_replace('\\', '/', $targetReal);
        }

        // Accept workspace-relative paths like themes/... or c/... sent by UI.
        $relative = ltrim($targetNormInput, '/');
        $baseCandidate = realpath(base_path($relative));
        if ($baseCandidate && is_dir($baseCandidate)) {
            $candidatePaths[] = str_replace('\\', '/', $baseCandidate);
        }

        $publicCandidate = realpath(public_path($relative));
        if ($publicCandidate && is_dir($publicCandidate)) {
            $candidatePaths[] = str_replace('\\', '/', $publicCandidate);
        }

        $candidatePaths = array_values(array_unique($candidatePaths));
        if (empty($candidatePaths)) {
            return null;
        }

        foreach ($candidatePaths as $targetNorm) {
            foreach ($roots as $rootNorm) {
                $prefix = rtrim(strtolower($rootNorm), '/').'/';
                if (strtolower($targetNorm) === strtolower($rootNorm) || str_starts_with(strtolower($targetNorm).'/', $prefix)) {
                    return $targetNorm;
                }
            }
        }

        return null;
    }

    private function getAllowedExtensionsForDirectory(int $communityId, string $dirPath): array
    {
        $dirNorm = strtolower(str_replace('\\', '/', trim($dirPath)));
        if ($dirNorm === '') {
            return ['html', 'js', 'css'];
        }

        $templateRoots = [];
        $templateRootPublic = realpath(public_path('themes/idh/default/views/templates/'.$communityId));
        if ($templateRootPublic && is_dir($templateRootPublic)) {
            $templateRoots[] = strtolower(str_replace('\\', '/', $templateRootPublic));
        }

        $templateRootBase = realpath(base_path('themes/idh/default/views/templates/'.$communityId));
        if ($templateRootBase && is_dir($templateRootBase)) {
            $templateRoots[] = strtolower(str_replace('\\', '/', $templateRootBase));
        }

        foreach (array_values(array_unique($templateRoots)) as $templateNorm) {
            $prefix = rtrim($templateNorm, '/').'/';
            if ($dirNorm === $templateNorm || str_starts_with($dirNorm.'/', $prefix)) {
                return ['html', 'css', 'js'];
            }
        }

        return ['html', 'js', 'css'];
    }

    private function buildNewThemeFileContent(string $ext, string $fileName, string $dirPath, bool $addHeader, bool $addFooter, string $pageTitle = ''): string
    {
        $ext = strtolower($ext);
        $safeTitle = trim($pageTitle) !== '' ? trim($pageTitle) : '';

        if ($ext === 'css') {
            return "/* {$fileName} */\n";
        }

        if ($ext === 'js') {
            return "// {$fileName}\n";
        }

        if ($ext === 'json') {
            return "{\n  \"name\": \"{$fileName}\"\n}\n";
        }

        if ($ext === 'xml') {
            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n</root>\n";
        }

        if ($ext === 'txt' || $ext === 'md') {
            return "";
        }

        $hasHeaderFile = is_file(rtrim($dirPath, '/').'/header.html');
        $hasFooterFile = is_file(rtrim($dirPath, '/').'/footer.html');

        $withHeader = $addHeader && $hasHeaderFile;
        $withFooter = $addFooter && $hasFooterFile;

        $parts = [];
        $parts[] = '<!DOCTYPE html>';
        $parts[] = '<html lang="en">';
        $parts[] = '    <head>';
        $parts[] = '        <meta charset="UTF-8">';
        $parts[] = '        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">';
        $parts[] = '        <title>'.htmlspecialchars($safeTitle, ENT_QUOTES, 'UTF-8').'</title>';
        if ($ext === 'html' || $ext === 'htm') {
            //$parts[] = '        <link rel="stylesheet" href="style.css">';
            //$parts[] = '        <link rel="stylesheet" href="dynamic.css">';
        }
        $parts[] = '    </head>';
        $parts[] = '    <body>';

       /* if ($ext === 'php' && $withHeader) {
            $parts[] = "        <?php include __DIR__ . '/header.php'; ?>";
        }*/
		
        if (($ext === 'html' || $ext === 'htm') && $withHeader) {
            $parts[] = '        <div id="aiwb-header-slot"></div>';
        }

        $parts[] = '        <main>';
        $parts[] = '            <section>';
        $parts[] = '                <h1>'.htmlspecialchars(pathinfo($fileName, PATHINFO_FILENAME), ENT_QUOTES, 'UTF-8').'</h1>';
        $parts[] = '            </section>';
        $parts[] = '        </main>';

       /* if ($ext === 'php' && $withFooter) {
            $parts[] = "        <?php include __DIR__ . '/footer.php'; ?>";
        }*/
		
        if (($ext === 'html' || $ext === 'htm') && $withFooter) {
            $parts[] = '        <div id="aiwb-footer-slot"></div>';
        }

        if ($ext === 'html' || $ext === 'htm') {
           /* $parts[] = '        <script src="script.js" defer></script>';
            $parts[] = '        <script src="dynamic.js" defer></script>';*/
        }

        $parts[] = '    </body>';
        $parts[] = '</html>';

        if ($ext === 'html' || $ext === 'htm') {
            return implode("\n", $parts)."\n";
        }

        return implode("\n", $parts)."\n";
    }

    private function cleanupThemeFileAiArtifactsForPath(int $communityId, string $forPath): void
    {
        if ($communityId <= 0 || trim($forPath) === '') {
            return;
        }

        $normalize = function (string $path): string {
            return str_replace('\\', '/', $path);
        };

        $target = strtolower($normalize($forPath));
        $root = storage_path('app/theme-file-ai/'.$communityId);
        if (! is_dir($root)) {
            return;
        }

        $dirs = [
            $root.'/results',
            $root.'/jobs',
        ];

        foreach ($dirs as $dir) {
            if (! is_dir($dir)) {
                continue;
            }

            $files = glob($dir.DIRECTORY_SEPARATOR.'*.json') ?: [];
            foreach ($files as $file) {
                $data = json_decode((string) @file_get_contents($file), true);
                if (! is_array($data)) {
                    continue;
                }

                $path = isset($data['path']) ? (string) $data['path'] : '';
                if ($path === '') {
                    $path = isset($data['path_url']) ? (string) $data['path_url'] : '';
                }

                if ($path !== '' && strtolower($normalize($path)) === $target) {
                    @unlink($file);
                }
            }
        }
    }

    public function themeFileToDelete(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');
        $community = $this->community;

        $path_url = $request->get('path_url');
        if ($path_url) {
           
		   /* $aiwbRoot = realpath(public_path('c/'.$community->id.'/web'));
            $targetPath = realpath($path_url);
            if ($aiwbRoot && $targetPath) {
                $aiwbRoot = rtrim($aiwbRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
                $targetPath = rtrim($targetPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
                if (str_starts_with($targetPath, $aiwbRoot)) {
                    return response('Not allowed', 403);
                }
            }*/
			
			$allowedPaths = [
				realpath(public_path('c/' . $community->id . '/web')),
				realpath(public_path('themes/idh/default/views/templates/' . $community->id)),
			];
			
			$targetPath = realpath($path_url);
			
			if (!$targetPath) {
				return response('Invalid path', 400);
			}
			
			$targetPath = rtrim($targetPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
			
			$matched = false;
			
			foreach ($allowedPaths as $allowedPath) {
				if (!$allowedPath) {
					continue;
				}
			
				$allowedPath = rtrim($allowedPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
			
				if (str_starts_with($targetPath, $allowedPath)) {
					$matched = true;
					break;
				}
			}
			
			if (!$matched) {
				return response('Not allowed', 403);
			}


            // unlink($path_url);
            if (is_dir($path_url)) {
                array_map('unlink', glob("$path_url/*.*"));
                rmdir($path_url);
            } else {
                unlink($path_url);
            }
        }
        // return redirect($this->community->present()->url());
    }

    public function programhighlights(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');

        return $this->render('community.pannel.cms.programhighlights', [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function termsconditions(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'homecms');

        return $this->render('community.pannel.cms.termsconditions', [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function makeAdvFeature(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $id = $request->get('id');
        $status = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityTopbannerRepository()->activateAdvertise($id, $status, $communityId);
    }

    public function deleteAdvertisement() {}

    public function socialfeed(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'socialfeed');

        $message = null;
        if ($val = $request->get('val')) {
            $this->communitySocialFeedRepository()->updateSocialFeed($val, $this->community->id);
            $message = 'Social ';
        }

        $social_feeds = $this->communitySocialFeedRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.socialfeed', ['social_feeds' => $social_feeds], [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function pages(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');
        $pages = $this->communityPagesRepository()->getAllByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.pages', ['pages' => $pages], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function addPage(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityPagesRepository()->addPage($val, $this->community->id);

            return redirect($this->community->present()->url('pages'));
        }
        $pagesmenus = $this->communityPagesRepository()->getAllPublishedMenusByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.add-page', ['pagesmenus' => $pagesmenus], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function editPage($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityPagesRepository()->editPage($val, $this->community->id, $pageId);

            return redirect($this->community->present()->url('pages'));
        }
        $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);
        $pagesmenus = $this->communityPagesRepository()->getAllPublishedMenusByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.edit-page', ['page' => $page, 'pagesmenus' => $pagesmenus], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function deletePage($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->communityPagesRepository()->deletePage($this->community->id, $pageId);

        return redirect($this->community->present()->url('pages'));
    }

    public function forms(Request $request)
    {
        $categories = $this->community->categories;
        $this->theme->share('settingPage', 'forms');
        $forms = $this->communityFormsRepository()->getAllByCommunityId($this->community->id, $this->community->present()->isAdminSubAdmin());

        return $this->render('community.pannel.cms.forms.index', ['forms' => $forms, 'categories' => $categories], [
            'title' => $this->setTitle('Forms'),
        ]);
    }

    public function addForm(Request $request)
    {
        $this->theme->share('settingPage', 'add_form');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityFormsRepository()->addForm($val, $this->community->id);

            return redirect($this->community->present()->url('forms'));
        }

        return $this->render('community.pannel.cms.forms.add-form', [
            'title' => $this->setTitle('Add Form'),
        ]);
    }

    public function addFormField($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'add_form_field');
        $message = null;
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        if ($val = $request->get('val')) {
            $this->customFieldRepository()->addFormField($val, $this->community->id);

            return redirect($this->community->present()->url('formfields').'/'.$form->id);
        }
        // $forms=$this->communityFormsRepository()->getAllByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.forms.add-form-field', ['form' => $form], [
            'title' => $this->setTitle('Add Form Field'),
        ]);
    }

    public function editForm($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'forms');
        $message = null;
        if ($val = $request->get('val')) {
            $form = $this->communityFormsRepository()->editForm($val, $this->community->id, $formId);
            if ($form->type == 0) {
                return redirect($this->community->present()->url('forms'));
            } else {
                \Session::flash('success_message', 'Nomination changes done successfully');

                return redirect($this->community->present()->url('longforms'));
            }
        }
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        return $this->render('community.pannel.cms.forms.edit-form', ['form' => $form], [
            'title' => $this->setTitle('Forms'),
        ]);
    }

    public function formFields($slug, $formId,Request $request)
    {
        $fields = $this->customFieldRepository()->getFormField('community-form', $this->community->id, $formId);
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        return $this->render('community.pannel.cms.forms.form-fields', ['form' => $form, 'fields' => $fields], [
            'title' => $this->setTitle('Forms'),
        ]);
    }

    public function editField($slug, $id,Request $request)
    {
        $field = $this->customFieldRepository()->get($id);

        if (! empty($field)) {
            $form = $this->communityFormsRepository()->getByIdComId($field->form_id, $this->community->id);
            if ($val = $request->get('val')) {
                $this->customFieldRepository()->saveFormField($val, $id);

                return redirect($this->community->present()->url('formfields').'/'.$form->id);
            }

            return $this->render('community.pannel.cms.forms.edit-form-field', ['form' => $form, 'field' => $field], [
                'title' => $this->setTitle('Forms'),
            ]);
        }
    }

    public function deleteField($slug, $id,Request $request)
    {
        $field = $this->customFieldRepository()->get($id);
        if (! empty($field)) {
            $form = $this->communityFormsRepository()->getByIdComId($field->form_id, $this->community->id);
            $this->customFieldRepository()->delete($id);

            return redirect($this->community->present()->url('formfields').'/'.$form->id);
        }
    }

    public function deleteForm($slug, $formId,Request $request)
    {
        $this->communityFormsRepository()->deleteForm($formId, $this->community->id);

        // return redirect($this->community->present()->url('forms'));
        return redirect(\URL::previous());
    }

    public function formPreview($slug, $formId,Request $request)
    {
        $fields = $this->customFieldRepository()->getFormFieldAll('community-form', $this->community->id, $formId);
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        return $this->render('community.pannel.cms.forms.form-preview', ['form' => $form, 'fields' => $fields], [
            'title' => $this->setTitle('Form Preview'),
        ]);
    }

    public function formDataCollected($slug, $formId,Request $request)
    {
        $type = $request->get('type');

        $fields = $this->customFieldRepository()->getFormFieldAll('community-form', $this->community->id, $formId);
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        if ($type == '' || $type == 0) {
            // $datas= $this->communityFormsSubmittedRepository()->getByFormComIdAll($formId,$this->community->id);
            $datas = $this->communityFormsSubmittedRepository()->getByFormComIdAll($formId, $this->community->id);
        } else {
            // $datas= $this->communityFormsSubmittedRepository()->getByFormComIdTypeAll($formId,$this->community->id,$type);
            $datas = $this->communityFormsSubmittedRepository()->getByFormComIdTypeAllData($formId, $this->community->id, $type);

            // $datas= $this->communityFormsReportsRepository()->getByFormComIdTypeAllList($formId,$this->community->id,$type);
        }

        return $this->render('community.pannel.cms.forms.data-collected', ['form' => $form, 'fields' => $fields, 'datas' => $datas, 'type' => $type], [
            'title' => $this->setTitle('Form Preview'),
        ]);
    }

    public function assignFormGroup(Request $request)
    {
        $formId = $request->get('id');
        $val = $request->get('val');

        $form = $this->communityFormsRepository()->assignFormGroup($formId, $this->community->id, $val);

        $this->communityFormsSeenRepository()->addData('form', $formId, $this->community->id, $val);
    }

    public function assignAdmin(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $this->communityMemberRepository()->assignAdmin($id, $value);
    }

    public function manageEmails(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $existingMembers = $this->communityMemberRepository()->listAllMembers($this->community->id);
        foreach ($existingMembers as $exMember) {
            if ($exMember->user) {
                $valEx = [
                    'name' => $exMember->user->fullname,
                    'email_address' => $exMember->user->email_address,
                    'is_member' => 1,
                ];

                $this->communityMembersEmailsRepository()->saveEmails($valEx, $this->community->id);
            }
        }

        return $this->render('community.pannel.emails',
            ['emails' => $this->communityMembersEmailsRepository()->listAll($this->community->id)],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function addEmail(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {
            $this->communityMembersEmailsRepository()->saveEmails($val, $this->community->id);

            return redirect($this->community->present()->url('manageemails'));
        }

        return $this->render('community.pannel.add-email',
            ['title' => $this->setTitle('Members')]
        );
    }

    public function deleteEmail($slug, $emailId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->communityMembersEmailsRepository()->deleteEmail($emailId, $this->community->id);

        return redirect($this->community->present()->url('manageemails'));
    }

    public function editEmail($slug, $emailId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {
            $this->communityMembersEmailsRepository()->editEmail($val, $this->community->id, $emailId);

            return redirect($this->community->present()->url('manageemails'));
        }

        $email = $this->communityMembersEmailsRepository()->getEmail($emailId, $this->community->id);

        return $this->render('community.pannel.edit-email',
            ['email' => $email],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function bulkEmailUpload(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        if ($request->hasFile('bulkemails')) {
            $countryManager = $request->get('countryManager');
            $bulkusers = $request->file('bulkemails');
            // require_once (app_path('library/Excel/Simplexlsx.class.php'));
            $xlsx = new SimpleXLSX($bulkusers);
            list($num_cols, $num_rows) = $xlsx->dimension();
            $f = 0;
            $processed = 0;
            $failedRecord = '';
            foreach ($xlsx->rows() as $r) {
                // Ignore the inital name row of excel file
                if ($f == 0) {
                    $f++;

                    continue;
                }

                for ($i = 0; $i < $num_cols; $i++) {
                    for ($i = 0; $i < $num_cols; $i++) {
                        if ($i == 0) {
                            $data['email_address'] = $r[$i];
                        } elseif ($i == 1) {
                            $data['name'] = $r[$i];
                        } elseif ($i == 2) {
                            $data['email_category'] = $r[$i];
                        }
                    }

                    if (isset($data)) {
                        if ($data['email_address'] != '') {
                            // if (filter_var($data['email_address'], FILTER_VALIDATE_EMAIL))
                            $email = trim($data['email_address']);
                            if ($this->valid_email($email)) {
                                $userFound = $this->communityMembersEmailsRepository()->getByCommunityEmail($email, $this->community->id);
                                if (empty($userFound)) {
                                    $processed++;
                                    $user = $this->communityMembersEmailsRepository()->saveEmails($data, $this->community->id);
                                } else {
                                    $failedRecord .= $email.', ';
                                }
                            }
                        }
                    }
                }
            }

            $failedMsg = '';
            if ($failedRecord != '') {
                $failedMsg = ' Records already exist for '.$failedRecord;
            }

            \Session::flash('msg', '<b>('.$processed.')</b>'.' records added.'.$failedMsg);
        }

        return redirect(\URL::previous());
    }

    public function valid_email($email)
    {

        if (is_array($email) || is_numeric($email) || is_bool($email) || is_float($email) || is_file($email) || is_dir($email) || is_int($email)) {
            return false;
        } else {
            $email = trim(strtolower($email));
            if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
                return $email;
            } else {
                $pattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';

                return (preg_match($pattern, $email) === 1) ? $email : false;
            }
        }
    }

    public function longForms(Request $request)
    {
        $categories = $this->community->categories;
        $this->theme->share('settingPage', 'forms');
        $forms = $this->communityFormsRepository()->getAllNominationByCommunityId($this->community->id, $this->community->present()->isAdminSubAdmin());

        return $this->render('community.pannel.cms.longforms.forms', ['forms' => $forms, 'categories' => $categories], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function addLongForm()
    {
        $this->theme->share('settingPage', 'add_form');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityFormsRepository()->addForm($val, $this->community->id);

            return redirect($this->community->present()->url('longforms'));
        }

        return $this->render('community.pannel.cms.longforms.add-form', [
            'title' => $this->setTitle('Add Form'),
        ]);
    }

    public function formCategories($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'Nomination');
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        $categories = $this->communityFormsCategoryRepository()->getByFormId($formId);

        return $this->render('community.pannel.cms.longforms.category', ['categories' => $categories, 'form' => $form], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function addFormCategory($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'Nomination');
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        if ($val = $request->get('val')) {
            $this->communityFormsCategoryRepository()->addCategory($val, $this->community->id, $formId);

            return redirect($this->community->present()->url('formcategories').'/'.$formId);
        }

        return $this->render('community.pannel.cms.longforms.add-category', ['form' => $form], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function editLongForm($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'forms');
        $message = null;
        if ($val = $request->get('val')) {
            $form = $this->communityFormsRepository()->editForm($val, $this->community->id, $formId);
            if ($form->type == 0) {
                return redirect($this->community->present()->url('forms'));
            } else {
                return redirect($this->community->present()->url('longforms'));
            }
        }
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        return $this->render('community.pannel.cms.longforms.edit-form', ['form' => $form], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function editFormCategory($slug, $categoryId,Request $request)
    {
        $this->theme->share('settingPage', 'forms');
        $message = null;
        $category = $this->communityFormsCategoryRepository()->getById($categoryId, $this->community->id);
        $form = $this->communityFormsRepository()->getByIdComId($category->form_id, $this->community->id);
        if ($val = $request->get('val')) {
            $category = $this->communityFormsCategoryRepository()->editCategory($val, $this->community->id, $categoryId);

            return redirect($this->community->present()->url('formcategories').'/'.$form->id);
        }

        return $this->render('community.pannel.cms.longforms.edit-category', ['category' => $category, 'form' => $form], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function surveyReport($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'Survey Report');
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($formId);
        $answers = $this->communityFormsAnswersRepository()->getByFormId($formId);

        return $this->render('community.pannel.cms.longforms.form-reports', ['categories' => $categories, 'form' => $form, 'answers' => $answers], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function votingReports($slug, $formId, $category_id,Request $request)
    {
        $this->theme->share('settingPage', 'Nomination and Votings');
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        $category = $this->communityFormsCategoryRepository()->getById($category_id, $this->community->id);
        $answers = $this->communityFormsAnswersRepository()->getAnswersByCategoryPaginate($formId, $category_id);

        return $this->render('community.pannel.cms.longforms.votings-reports', ['category' => $category, 'form' => $form, 'answers' => $answers], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function deleteFormCategory($slug, $formId, $category_id)
    {
        $this->communityFormsCategoryRepository()->deleteFormCategory($formId, $category_id, $this->community->id);

        return redirect(\URL::previous());
    }

    public function setNominationLimit(Request $request)
    {
        $formId = $request->get('id');
        $val = $request->get('val');

        $form = $this->communityFormsRepository()->setNominationLimit($formId, $this->community->id, $val);
    }

    public function updateNominationDetails(Request $request)
    {
        $id = $request->get('id');
        $weburl = $request->get('weburl');
        $description = $request->get('description');
        $formid = $request->get('formid');
        $categoryid = $request->get('categoryid');
        $answer = $request->get('answer');

        $this->communityFormsAnswersRepository()->updateNominationDetails($this->community->id, $id, $weburl, $description, $formid, $categoryid, $answer);
    }

    public function nominationReports($slug, $formId, $category_id,Request $request)
    {
        $this->theme->share('settingPage', 'Nomination Reports');
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        $category = $this->communityFormsCategoryRepository()->getById($category_id, $this->community->id);
        $answers = $this->communityFormsAnswersRepository()->getAllAnswersByCategory($formId, $category_id);

        return $this->render('community.pannel.cms.longforms.nominations-reports', ['category' => $category, 'form' => $form, 'answers' => $answers], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function manageSurveyEmails(Request $request)
    {
        if ($this->community->present()->isAdminSubAdmin()) {
            return $this->render('community.pannel.cms.longforms.emails',
                ['emails' => $this->communityMembersEmailsRepository()->surveyEmailsListAll($this->community->id)],
                ['title' => $this->setTitle(trans('formsurveys.business-contacts'))]
            );
        } else {
            redirect('home')->send();
        }
    }

    public function addSurveyEmail(Request $request)
    {
        if ($this->community->present()->canManage()) {
            $message = null;
            if ($val = $request->get('val')) {
                $this->communityMembersEmailsRepository()->saveSurveyEmails($val, $this->community->id);

                return redirect($this->community->present()->url('managesurveyemails'));
            }

            return $this->render('community.pannel.cms.longforms.add-email',
                ['title' => $this->setTitle(trans('formsurveys.business-contacts'))]
            );
        } else {
            redirect('home')->send();
        }
    }

    public function deleteSurveyemail($slug, $emailId,Request $request)
    {
        $this->communityMembersEmailsRepository()->deleteSurveyemail($emailId, $this->community->id);

        return redirect($this->community->present()->url('managesurveyemails'));
    }

    public function editSurveyEmail($slug, $emailId,Request $request)
    {
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityMembersEmailsRepository()->editSurveyEmail($val, $this->community->id, $emailId);

            return redirect($this->community->present()->url('managesurveyemails'));
        }

        $email = $this->communityMembersEmailsRepository()->getSurveyEmail($emailId, $this->community->id);

        return $this->render('community.pannel.cms.longforms.edit-email',
            ['email' => $email],
            ['title' => $this->setTitle(trans('formsurveys.business-contacts'))]
        );
    }

    public function bulkSurveyEmailUpload(Request $request)
    {
        if ($request->hasFile('bulkemails')) {
            $bulkusers = $request->file('bulkemails');
            // require_once (app_path('library/Excel/Simplexlsx.class.php'));
            $xlsx = new SimpleXLSX($bulkusers);
            list($num_cols, $num_rows) = $xlsx->dimension();
            $f = 0;
            $processed = 0;
            $failedRecord = '';
            foreach ($xlsx->rows() as $r) {
                // Ignore the inital name row of excel file
                if ($f == 0) {
                    $f++;

                    continue;
                }

                for ($i = 0; $i < $num_cols; $i++) {
                    for ($i = 0; $i < $num_cols; $i++) {
                        if ($i == 0) {
                            $data['email_address'] = $r[$i];
                        } elseif ($i == 1) {
                            $data['name'] = $r[$i];
                        } elseif ($i == 2) {
                            $data['survey_category'] = $r[$i];
                        }
                    }

                    if (isset($data)) {
                        if ($data['email_address'] != '') {
                            // if (filter_var($data['email_address'], FILTER_VALIDATE_EMAIL))
                            $email = trim($data['email_address']);
                            $survey_category = '';
                            if (isset($data['survey_category'])) {
                                $survey_category = $data['survey_category'];
                            }

                            if ($this->valid_email($email)) {
                                $userFound = $this->communityMembersEmailsRepository()->getByCommunityEmailSurvey($email, $this->community->id, $survey_category);
                                if (empty($userFound)) {
                                    $processed++;
                                    $user = $this->communityMembersEmailsRepository()->saveSurveyEmails($data, $this->community->id);
                                } else {
                                    $failedRecord .= $email.', ';
                                }
                            }
                        }
                    }
                }
            }

            $failedMsg = '';
            if ($failedRecord != '') {
                $failedMsg = ' Records already exist for '.$failedRecord;
            }

            \Session::flash('msg', '<b>('.$processed.')</b>'.' records added.'.$failedMsg);
        }

        return redirect(\URL::previous());
    }

    public function surveyInvite($slug, $formId,Request $request)
    {
        $message = null;
        $this->theme->share('settingPage', 'Survey invite');
        $message = null;

        if ($val = $request->get('val')) {
            $this->inviteRepository()->inviteForSurvey($val, null, null, $this->community);
            $message = trans('formsurveys.survey-invite-email-sent');
        }

        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);
        $contactsCategory = $this->communityMembersEmailsRepository()->getByCommunityEmailSurveyList($this->community->id);

        return $this->render('community.pannel.cms.longforms.survey-invite', ['form' => $form, 'message' => $message, 'contactsCategory' => $contactsCategory], [
            'title' => $this->setTitle(trans('formsurveys.forms')),
        ]);
    }

    public function deleteNomination($slug, $formId, $category_id, $answer_id)
    {
        $this->communityFormsAnswersRepository()->deleteNomination($formId, $category_id, $answer_id);

        return redirect(\URL::previous());
    }

    public function updateNomination($slug, $formId, $category_id, $answer_id)
    {
        $answer = $request->get('answer');
        $this->communityFormsAnswersRepository()->updateNomination($formId, $category_id, $answer_id, $answer);
    }

    public function socialMediaLogins(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'socialmedialogins');

        $message = null;
        if ($val = $request->get('val')) {
            $this->communitySocialMediaLoginsRepository()->updateSocialMediaLogins($val, $this->community->id);
            $message = 'Social ';
        }

        $socialmedialogins = $this->communitySocialMediaLoginsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.socialmedialogins', ['socialmedialogins' => $socialmedialogins], [
            'title' => $this->setTitle(trans('organizationdashboard.social-media-logins')),
        ]);
    }
	
	public function pagesHeaders(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesheaders');

		if ($val = $request->get('val')) {

            $addContents = $this->communityHomeContentsRepository()->addHeaderContents($val, $this->community, \Auth::user()->id);
        }

        $headerSlugs = ['login', 'signup', 'post', 'business', 'events', 'news', 'surveys', 'award', 'chamber_directory', 'chamber_profile','chamber_registration'];
        $pageHeaderHasThemeText = [];
        foreach ($headerSlugs as $slug) {
            $header = $this->communityPagesRepository()->getByIdComIdHeaderPage($slug, $this->community->id);
            $pageHeaderHasThemeText[$slug] = $header && trim((string) ($header->html_edit_code_theme2 ?? '')) !== '';
        }
		
		$contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.pages.pages-headers', [
            'pageHeaderHasThemeText' => $pageHeaderHasThemeText,
			'contents'=>$contents,
        ], [
            'title' => $this->setTitle(trans('cms.pages-headers')),
        ]);
    }

    public function masterHeader(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesheaders');

        $homecontents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);
        $pages = $this->community->present()->getPages();

        $editData = '';
        if ($homecontents && ! empty($homecontents->chamber_common_header_html)) {
            $editData = (string) $homecontents->chamber_common_header_html;
        } elseif ($homecontents && ! empty($homecontents->html_edit_code_chamber)) {
            $editData = (string) extractChamberCommonHeaderSection($homecontents->html_edit_code_chamber);
        }

        if ($editData === '') {
            $community = $this->community;
            $defaultHeader = include resource_path('views/themes/frontend/default/views/community/pannel/cms/pages/chamber-default-header.blade.php');
            $editData = (string) extractChamberCommonHeaderSection($defaultHeader);
        }

        // Render with tokens resolved for preview in the editor (save JS will persist tokens back).
        $editData = replaceCommunityHeaderTokens($editData, $this->community, $homecontents, $pages);

        return $this->render('community.pannel.cms.pages.master-header', [
            'homecontents' => $homecontents,
            'pages' => $pages,
            'editData' => $editData,
        ], [
            'title' => $this->setTitle('Master Header'),
        ]);
    }

    public function saveMasterHeader(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $pagehtml = (string) $request->get('pagehtml');
        $this->communityHomeContentsRepository()->saveCommonHeaderHtml($this->community->id, $pagehtml, \Auth::user()->id);

        \Session::flash('success', 'Setting saved successfully');

        return $this->community->present()->url('masterheader?vieweditor=editor');
    }

    public function masterHeaderPreview(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $homecontents = $this->community->present()->getHomeContents();
        $pages = $this->community->present()->getPages();
        $feviconImage = $this->community->present()->getFeviconAvatar();

        $contents = '';
        if ($homecontents && ! empty($homecontents->chamber_common_header_html)) {
            $contents = (string) $homecontents->chamber_common_header_html;
        } elseif ($homecontents && ! empty($homecontents->html_edit_code_chamber)) {
            $contents = (string) extractChamberCommonHeaderSection($homecontents->html_edit_code_chamber);
        }

        if ($contents === '') {
            $community = $this->community;
            $defaultHeader = include resource_path('views/themes/frontend/default/views/community/pannel/cms/pages/chamber-default-header.blade.php');
            $contents = (string) extractChamberCommonHeaderSection($defaultHeader);
        }

        return response()
            ->view('themes.frontend.default.views.community.pannel.cms.pages.master-header-preview-iframe', [
                'community' => $this->community,
                'homecontents' => $homecontents,
                'pages' => $pages,
                'feviconImage' => $feviconImage,
                'contents' => $contents,
            ])
            ->header('X-Frame-Options', 'SAMEORIGIN')
            ->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
    }
	
	public function pagesFooter(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesfooter');

		if ($val = $request->get('val')) {

            $addContents = $this->communityHomeContentsRepository()->addFooterContents($val, $this->community, \Auth::user()->id);
        }
		
        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);
		
        return $this->render('community.pannel.cms.pages.pages-footer', [
           'contents'=>$contents,
        ], [
            'title' => $this->setTitle(trans('cms.footer-settings')),
        ]);
    }

    public function defaultHeaderPreview(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $homecontents = $this->community->present()->getHomeContents();
        $pages = $this->community->present()->getPages();
        $feviconImage = $this->community->present()->getFeviconAvatar();

        // Force the website theme for this iframe so Theme::asset()/Theme::section() render correctly.
        $this->theme = \Theme::type('idh')
            ->current(\ThemeManager::getActive('idh'))
            ->reBoot()
            ->layout('layouts.default');
        $this->theme->share('community', $this->community);
        $this->theme->share('homecontents', $homecontents);
        $this->theme->share('pages', $pages);
        $this->theme->share('feviconImage', $feviconImage);

        return response()
            ->view('themes.idh.default.views.community.pannel.cms.pages.default-header-preview-iframe', [
                'community' => $this->community,
                'homecontents' => $homecontents,
                'pages' => $pages,
                'feviconImage' => $feviconImage,
            ])
            ->header('X-Frame-Options', 'SAMEORIGIN')
            ->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
    }

    public function pagesMenus(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesmenus');
        $pages = $this->communityPagesRepository()->getAllMenusByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.pages-menus-list', ['pages' => $pages], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function pagesMenuAdd(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesmenuadd');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityPagesRepository()->addPage($val, $this->community->id);

            return redirect($this->community->present()->url('pagesmenus'));
        }

        return $this->render('community.pannel.cms.add-page-menu', [
            'title' => $this->setTitle('Add Menu'),
        ]);
    }

    public function pagesMenuSrno(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesmenusrno');
        $message = null;
        if ($val = $request->get('val')) {
            $menus = $request->get('page');

            $this->communityHomeContentsRepository()->addMenuSequence($val, $this->community->id);
            $this->communityPagesRepository()->addMenuSequence($menus, $this->community->id);
            \Session::flash('message', trans('organizationpages.menu-sequence-changed-successfully'));

            return redirect($this->community->present()->url('pagesmenusrno'));
        }

        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);
        $pagesmenus = $this->communityPagesRepository()->getAllMenusByCommunityId($this->community->id);
        $pages = $this->communityPagesRepository()->getAllByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.page-menus-srno', ['contents' => $contents, 'pagesmenus' => $pagesmenus, 'pages' => $pages], [
            'title' => $this->setTitle(trans('organizationpages.menu-sequence')),
        ]);
    }

    public function signupPageSetting(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'Signup Page Setting');
        $message = null;
        if ($val = $request->get('val')) {
            $menus = $request->get('page');
            $this->communityHomeContentsRepository()->signupPageSettings($val, $this->community->id);
            \Session::flash('success', 'Settings saved successfully');

            return redirect($this->community->present()->url('signuppagesetting'));
        }

        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.signup-page-settings', ['contents' => $contents], [
            'title' => $this->setTitle('Signup Page Setting'),
        ]);
    }

    public function deletePageMenu($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $this->communityPagesRepository()->deletePage($this->community->id, $pageId);

        return redirect($this->community->present()->url('pagesmenus'));
    }

    public function editPageMenu($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesmenu');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityPagesRepository()->editPage($val, $this->community->id, $pageId);

            return redirect($this->community->present()->url('pagesmenus'));
        }
        $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);

        return $this->render('community.pannel.cms.edit-page-menu', ['page' => $page], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function copyForm($slug, $formId,Request $request)
    {
        $this->theme->share('settingPage', 'forms');
        $this->communityFormsRepository()->copyForm($formId, $this->community->id);

        return redirect(\URL::previous());
    }

    public function campaigns(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $campaigns = $this->communityCampaignRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.campaigns', ['campaigns' => $campaigns], [
            'title' => $this->setTitle(trans('campaign.sent-campaigns')),
        ]);
    }

    public function campaignTemplates(Request $request)
    {
        // Campaign

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'templates');
        $templates = $this->communityCampaignTemplatesRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.template.templates', ['templates' => $templates], [
            'title' => $this->setTitle(trans('campaign.start')),
        ]);
    }

    public function addCampaignTemplate(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        return $this->render('community.pannel.campaigns.template.add-template', [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function saveCampaignTemplate(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $templateTitle = $request->get('templateTitle');
        $pagename = $request->get('pagename');

        $template = $this->communityCampaignTemplatesRepository()->saveTemplate($templateTitle, $pagename, $this->community);

        return $this->community->present()->url('campaigntemplates');
    }

    public function updateCampaignTemplate(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $templateTitle = $request->get('templateTitle');
        $pagename = $request->get('pagename');
        $id = $request->get('id');

        $template = $this->communityCampaignTemplatesRepository()->updateTemplate($templateTitle, $pagename, $this->community, $id);

        return $this->community->present()->url('campaigntemplates');
    }

    public function deleteTemplate($slug, $id)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->communityCampaignTemplatesRepository()->deleteTemplate($this->community->id, $id);

        return redirect(\URL::previous());
    }

    public function previewtemplate($slug, $templateId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $template = $this->communityCampaignTemplatesRepository()->getByIdComId($templateId, $this->community->id);

        $footer = $this->communityCampaignTemplatesFooterRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.template.template-preview', ['template' => $template, 'footer' => $footer], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function editTemplate($slug, $templateId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $template = $this->communityCampaignTemplatesRepository()->getByIdComId($templateId, $this->community->id);

        return $this->render('community.pannel.campaigns.template.edit-template', ['template' => $template], [
            'title' => $this->setTitle('Templates'),
        ]);
    }

    public function addCampaign(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        /*        if ($val = $request->get('val')) {
                    $this->communityCampaignRepository()->addCampaign($val, $this->community->id,$this->community);
                      return redirect($this->community->present()->url('campaigns'));
                }
        */

        $template_id = $request->get('template_id');

        if ($template_id) {
            $template = $this->communityCampaignTemplatesRepository()->getByIdComId($template_id, $this->community->id);
        } else {
            $template_id = 0;
            $template = '';
        }

        return $this->render('community.pannel.campaigns.add-campaign', ['template_id' => $template_id, 'template' => $template], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function updateCampaign(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $templateTitle = $request->get('templateTitle');
        $pagename = $request->get('pagename');
        $id = $request->get('id');

        $template = $this->communityCampaignRepository()->updateCampaign($templateTitle, $pagename, $this->community, $id);

        return $this->community->present()->url('campaigns');
    }

    public function updateCampaignSaved(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $pagename = $request->get('pagename');
        $campaign_id = $request->get('campaign_id');

        $campaign = $this->communityCampaignRepository()->getByIdComId($campaign_id, $this->community->id);
        if ($campaign) {
            return $this->communityCampaignRepository()->savePageHtmlData($campaign);
        }
    }

    public function saveCampaign(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $campaignTitle = $request->get('campaignTitle');
        $pagename = $request->get('pagename');
        $template_id = $request->get('template_id');

        $template = $this->communityCampaignRepository()->saveCampaign($campaignTitle, $pagename, $this->community, $template_id);

        return $this->community->present()->url('campaigns');
    }

    public function editCampaign($slug, $campaignId,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityCampaignRepository()->editCampaign($val, $this->community->id, $campaignId);

            return redirect($this->community->present()->url('campaigns'));
        }
        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);

        return $this->render('community.pannel.campaigns.edit-campaign', ['campaign' => $campaign], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function deleteCampaign($slug, $id)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->communityCampaignRepository()->deleteCampaign($this->community->id, $id);

        return redirect($this->community->present()->url('campaigns'));
    }

    public function campaignMailingCat()
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $this->theme->share('settingPage', 'campaignscategories');
        $campaignsCategories = $this->communityCampaignMailingCategoryRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.mailing-categories', ['campaignsCategories' => $campaignsCategories], [
            'title' => $this->setTitle(trans('campaign.target-category')),
        ]);
    }

    public function addCampaignCategory(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityCampaignMailingCategoryRepository()->addCategory($val, $this->community->id);

            return redirect($this->community->present()->url('campaignmailingcat'));
        }

        return $this->render('community.pannel.campaigns.add-mailing-category', [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function editCampaignCategory($slug, $categoryId,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityCampaignMailingCategoryRepository()->editCategory($val, $this->community->id, $categoryId);

            return redirect($this->community->present()->url('campaignmailingcat'));
        }
        $category = $this->communityCampaignMailingCategoryRepository()->getByIdComId($categoryId, $this->community->id);

        return $this->render('community.pannel.campaigns.edit-mailing-category', ['category' => $category], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function deleteCampaignCategory($slug, $id)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->communityCampaignMailingCategoryRepository()->deleteCampaignCategory($this->community->id, $id);

        return redirect($this->community->present()->url('campaignmailingcat'));
    }

    public function manageCampaignEmails($slug, $id,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $term = $request->get('term');

        $this->theme->share('settingPage', 'campaigns');
        $category = $this->communityCampaignMailingCategoryRepository()->getByIdComId($id, $this->community->id);

        return $this->render('community.pannel.campaigns.emails-list',
            [
                'emails' => $this->communityMembersEmailsRepository()->listAllByCampainCategory($this->community->id, $id, $term),
                'category' => $category,
                'term' => $term],
            ['title' => $this->setTitle(trans('campaign.campaign-emails'))]
        );
    }

    public function addCampainEmails($slug, $id,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityMembersEmailsRepository()->saveCampaignEmails($val, $this->community->id);

            return redirect($this->community->present()->url('managecampaignemails').'/'.$id);
        }

        $category = $this->communityCampaignMailingCategoryRepository()->getByIdComId($id, $this->community->id);

        return $this->render('community.pannel.campaigns.add-email', ['category' => $category],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function bulkCampaignEmailUpload(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        if ($request->hasFile('bulkemails')) {
            $campaign_category_id = $request->get('campaign_category_id');
            $bulkusers = $request->file('bulkemails');
            // require_once (app_path('library/Excel/Simplexlsx.class.php'));
            $xlsx = new SimpleXLSX($bulkusers);
            list($num_cols, $num_rows) = $xlsx->dimension();
            $f = 0;
            $processed = 0;
            $failedRecord = '';
            foreach ($xlsx->rows() as $r) {
                // Ignore the inital name row of excel file
                if ($f == 0) {
                    $f++;

                    continue;
                }

                for ($i = 0; $i < $num_cols; $i++) {
                    for ($i = 0; $i < $num_cols; $i++) {
                        if ($i == 0) {
                            $data['email_address'] = $r[$i];
                        } elseif ($i == 1) {
                            $data['name'] = $r[$i];
                        } elseif ($i == 2) {
                            $data['last_name'] = $r[$i];
                        } elseif ($i == 3) {
                            $data['company'] = $r[$i];
                        } elseif ($i == 4) {
                            $data['designation'] = $r[$i];
                        } elseif ($i == 5) {
                            $data['mobile_number'] = $r[$i];
                        } elseif ($i == 6) {
                            $data['contact'] = $r[$i];
                        } elseif ($i == 7) {
                            $data['website_url'] = $r[$i];
                        } elseif ($i == 8) {
                            $data['about_org'] = $r[$i];
                        } elseif ($i == 9) {
                            $data['address'] = $r[$i];
                        } elseif ($i == 10) {
                            $data['other'] = $r[$i];
                        }
                    }

                    if (isset($data)) {
                        if ($data['email_address'] != '') {
                            // if (filter_var($data['email_address'], FILTER_VALIDATE_EMAIL))
                            $email = trim($data['email_address']);

                            $data['campaign_category_id'] = $campaign_category_id;

                            if ($this->valid_email($email)) {
                                $userFound = $this->communityMembersEmailsRepository()->getByCommunityEmailCampaign($email, $this->community->id, $campaign_category_id);
                                if (empty($userFound)) {
                                    $processed++;
                                    $user = $this->communityMembersEmailsRepository()->saveCampaignEmails($data, $this->community->id);
                                } else {
                                    $failedRecord .= $email.', ';
                                }
                            }
                        }
                    }
                }
            }

            $failedMsg = '';
            if ($failedRecord != '') {
                $failedMsg = ' Records already exist for '.$failedRecord;
            }

            \Session::flash('msg', '<b>('.$processed.')</b>'.' records added.'.$failedMsg);
        }

        return redirect(\URL::previous());
    }

    public function deleteCampaignEmail($slug, $emailId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->communityMembersEmailsRepository()->deleteCampaignEmail($emailId, $this->community->id);

        return redirect(\URL::previous());
    }

    public function editCampaignEmail($slug, $emailId, $category_id,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $message = null;
        if ($val = $request->get('val')) {
            $this->communityMembersEmailsRepository()->editCampaignEmail($val, $this->community->id, $emailId);

            return redirect($this->community->present()->url('managecampaignemails').'/'.$category_id);
        }

        $email = $this->communityMembersEmailsRepository()->getCampaignEmail($emailId, $this->community->id);
        $category = $this->communityCampaignMailingCategoryRepository()->getByIdComId($category_id, $this->community->id);

        return $this->render('community.pannel.campaigns.edit-email', ['category' => $category, 'email' => $email],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function emailCampaign(Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        if ($val = $request->get('val')) {
            $this->communityCampaignEmailsRepository()->sendEmail($val, $this->community);
            \Session::flash('msg', 'Emails sent successfully');

            return redirect(\URL::previous());
        }

        $categories = $this->communityCampaignMailingCategoryRepository()->getAllByCommunityId($this->community->id);
        $campaigns = $this->communityCampaignRepository()->getAllByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.email-campaign', ['categories' => $categories, 'campaigns' => $campaigns],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function previewCampaign($slug, $campaignId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);

        return $this->render('community.pannel.campaigns.campaign-preview', ['campaign' => $campaign], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function campaignHistory()
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $records = $this->communityCampaignEmailsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.campaign-history', ['records' => $records], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function templateHistory()
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $records = $this->communityCampaignEmailsRepository()->getByCommunityIdTemplate($this->community->id);

        return $this->render('community.pannel.campaigns.template.template-history', ['records' => $records], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function campaignEmailreport($slug, $emailId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $emailRecord = $this->communityCampaignEmailsRepository()->getById($emailId);
        $records = $this->communityCampaignEmailsSentRepository()->getByCommunityId($emailId, $this->community->id);

        return $this->render('community.pannel.campaigns.campaign-email-report', ['records' => $records, 'emailRecord' => $emailRecord], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function templateEmailReport($slug, $emailId)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $emailRecord = $this->communityCampaignEmailsRepository()->getById($emailId);
        $records = $this->communityCampaignEmailsSentRepository()->getByCommunityId($emailId, $this->community->id);

        return $this->render('community.pannel.campaigns.template.template-email-report', ['records' => $records, 'emailRecord' => $emailRecord], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function exportCmFormdata($slug, $formId,Request $request)
    {
        $type = $request->get('type');

        $fields = $this->customFieldRepository()->getFormFieldAll('community-form', $this->community->id, $formId);
        $form = $this->communityFormsRepository()->getByIdComId($formId, $this->community->id);

        if ($type == '' || $type == 0) {
            $datas = $this->communityFormsSubmittedRepository()->getByFormComIdAll($formId, $this->community->id);
        } else {
            $datas = $this->communityFormsSubmittedRepository()->getByFormComIdTypeAllData($formId, $this->community->id, $type);
        }

        $columnNames = [];
        foreach ($fields as $field) {
            array_push($columnNames, trans($field->name));
        }

        $array_data[] = $columnNames;

        foreach ($datas as $data) {
            $info = perfectUnserialize($data->data);
            $dataCollected = [];
            foreach ($fields as $field) {
                if (isset($info[$field->id])) {
                    if ($field->field_type == 'file') {
                        // $fileUrl="<a href='".$this->community->present()->getDocumentUrl($info[$field->id])."'>View File</a>";
                        $fileUrl = $this->community->present()->getDocumentUrl($info[$field->id]);
                        array_push($dataCollected, $fileUrl);
                    } else {
                        array_push($dataCollected, $info[$field->id]);
                    }
                }
            }
            $array_data[] = $dataCollected;
        }

        $excelFileName = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $form->title)));
        $this->exportAsExcel($array_data, $excelFileName);
    }

    public function exportAsExcel($export_data, $file_name)
    {
        // require_once(app_path('library/PHPExcel/PHPExcel.php'));
        require_once base_path('functions/PHPExcel/PHPExcel.php');
        // create php excel object
        $doc = new \PHPExcel;

        // set active sheet
        $doc->setActiveSheetIndex(0);

        $doc->getActiveSheet()->fromArray($export_data);
        $doc->getActiveSheet()->getStyle('A1:T1')->getFont()->setBold(true);
        // save our workbook as this file name

        $fName = $file_name.'-'.date('d-m-Y');
        $filename = $fName.'.xlsx';
        // mime type

        header('Content-Type: application/vnd.ms-excel');
        // tell browser what's the file name
        header('Content-Disposition: attachment;filename="'.$filename.'"');

        header('Cache-Control: max-age=0'); // no cache
        // save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
        // if you want to save it as .XLSX Excel 2007 format

        $objWriter = \PHPExcel_IOFactory::createWriter($doc, 'Excel2007');

        // force user to download the Excel file without writing it to server's HD
        ob_end_clean();
        $objWriter->save('php://output');
        exit;
    }

    public function onlineMembers()
    {
        $members = $this->userRepository()->getOnlineUsersByCommunity($this->community->id);
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        return $this->render('community.pannel.online-members', ['members' => $members], ['title' => $this->setTitle('Online Members')]);
    }

    public function unverifiedMembers()
    {
        $members = $this->userRepository()->listUnverifiedUsers(null, $this->community->id);
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        return $this->render('community.pannel.unverified-members', ['members' => $members], ['title' => $this->setTitle(trans('organizationdashboard.unverified-members'))]);
    }

    public function manageDefaultRss(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;

        if ($val = $request->get('val')) {
            $community->default_rss_categories = perfectSerialize(sanitizeUserInfo($val));
            $community->save();
        }

        $categories = $this->rssFeedsCategoriesRepository()->getAll();

        return $this->render('community.pannel.default-rss-categories', ['categories' => $categories], ['title' => $this->setTitle('Default RSS Categories')]);
    }

    public function sendVerificationEmail(Request $request)
    {
        $userid = $request->get('userid');
        $user = $this->userRepository()->findById($userid);
        if ($user and $user->is_email_verified == 0) {
            $this->userRepository()->sendVerificationEmail($user);
            $verificationSend = 'Verification email sent to '.$user->email_address;

            \Session::flash('success', $verificationSend);

            return redirect($this->community->present()->url('unverifiedmembers'));
        } else {
            $verificationSend = 'Invalid request';

            return redirect($this->community->present()->url('unverifiedmembers'));
        }
    }

    public function menuHeadings(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');

        if ($val = $request->get('val')) {
            $addContents = $this->communityHomeContentsRepository()->addMenuTitles($val, $this->community->id);

            return redirect($this->community->present()->url('menuheadings'));
        }

        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.static-menu-edit', ['contents' => $contents], [
            'title' => $this->setTitle('Home CMS'),
        ]);
    }

    public function eMarketplace(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'emarketplace');

        if ($val = $request->get('val')) {
            $addContents = $this->communityBusinessSettingsRepository()->addeMarketplace($val, $this->community->id);

            return redirect($this->community->present()->url('emarketplace'));
        }

        $contents = $this->communityBusinessSettingsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.emarketplace', ['contents' => $contents], [
            'title' => $this->setTitle(trans('organizationsettings.eMarketplace')),
        ]);
    }

    public function cmSurveys()
    {
        if ($this->community->present()->isAdminSubAdmin()) {
            $surveys = $this->communitySurveysRepository()->getSurveys($this->community->id);
        } else {
            $surveys = $this->communitySurveysRepository()->getSurveysByUserId($this->community->id, \Auth::user()->id);
        }

        $categories = $this->community->categories;

        return $this->render('community.pannel.cms.surveys.index', ['surveys' => $surveys, 'categories' => $categories], [
            'title' => $this->setTitle(trans('formsurveys.community-surveys')),
        ]);
    }

    public function addSurvey()
    {
        return $this->render('community.pannel.cms.surveys.add-survey', ['surveys' => ''], [
            'title' => $this->setTitle(trans('formsurveys.community-surveys')),
        ]);
    }

    public function add_survey(Request $request)
    {
        if ($val = $request->get('val')) {
            $survey = $this->communitySurveysRepository()->addSurvey($val, $this->community->id);

            if ($survey) {
                $questions = $this->communitySurveyQuestionsRepository()->getQuestions($survey->id, $this->community->id);

                return (string) $this->theme->section('community.pannel.cms.surveys.survey-info', ['survey' => $survey, 'questions' => $questions]);
            }
        }
    }

    public function manageSurvey($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {

            // $questions=$this->communitySurveyQuestionsRepository()->getQuestions($surveyId,$this->community->id);

            $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($surveyId, $this->community->id);

            return $this->render('community.pannel.cms.surveys.manage-survey', ['survey' => $survey, 'questions' => $questions], [
                'title' => $this->setTitle(trans('formsurveys.manage-surveys')),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function generateQuestion($slug, $surveyId,Request $request)
    {
        $type = $request->get('type');
        $questionid = $request->get('questionid');
        $mainquestionid = $request->get('mainquestionid');

        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        if ($survey) {
            $options = '';
            $question = $this->communitySurveyQuestionsRepository()->addQuestion($type, $questionid, $surveyId, $this->community->id, $mainquestionid);

            if ($question and $type == 'choice') {
                $this->communitySurveyQuestionOptionsRepository()->addOptions($question);
            }

            /* return (String) $this->theme->section('community.pannel.cms.surveys.generate-question', ['survey' => $survey,'question'=>$question,'srNo'=>$questionid]); */

            return (string) $this->theme->section('community.pannel.cms.surveys.generate-question', ['survey' => $survey, 'question' => $question, 'srNo' => $question->srno]);
        }
    }

    public function changeMultiOption(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->changeMultiOption($id, $value, $this->community->id);
    }

    public function changeAnswerOption(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->changeAnswerOption($id, $value, $this->community->id);
    }

    public function changeRequiredOption(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->changeRequiredOption($id, $value, $this->community->id);
    }

    public function updateSurveyQuestion(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->updateSurveyQuestion($id, $value, $this->community->id);
    }

    public function updateSurveyPlaceholder(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->updateSurveyPlaceholder($id, $value, $this->community->id);
    }

    public function updateSurveyAnswerOption(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionOptionsRepository()->updateSurveyAnswerOption($id, $value, $this->community->id);
    }

    public function updateQuestionSrno(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->updateQuestionSrno($id, $value, $this->community->id);
    }

    public function addAnswerOption(Request $request)
    {
        $id = $request->get('id');

        $question = $this->communitySurveyQuestionsRepository()->getById($id, $this->community->id);
        $optionType = $question->multiple_option;
        $optionTypeName = 'radio';
        if ($optionType == 1) {
            $optionTypeName = 'checkbox';
        } elseif ($optionType == 3) {
            $optionTypeName = 'list';
        }

        $options = $this->communitySurveyQuestionOptionsRepository()->addOptions($question, 2);

        return (string) $this->theme->section('community.pannel.cms.surveys.options', ['questionid' => $id, 'optionTypeName' => $optionTypeName, 'options' => $options, 'option_type' => $question->multiple_option]);
    }

    public function deleteSurveyOption(Request $request)
    {
        $oid = $request->get('oid');
        $id = $request->get('id');

        $question = $this->communitySurveyQuestionsRepository()->getById($id, $this->community->id);
        $optionType = $question->multiple_option;
        $optionTypeName = 'radio';
        if ($optionType == 1) {
            $optionTypeName = 'checkbox';
        } elseif ($optionType == 3) {
            $optionTypeName = 'list';
        }

        $this->communitySurveyQuestionOptionsRepository()->deleteOption($oid, $this->community->id);

        $options = $this->communitySurveyQuestionOptionsRepository()->getByQuestionId($id);

        return (string) $this->theme->section('community.pannel.cms.surveys.options', ['questionid' => $id, 'optionTypeName' => $optionTypeName, 'options' => $options, 'option_type' => $question->multiple_option]);
    }

    public function updateSurveyOptionQuestion(Request $request)
    {
        $id = $request->get('id');
        $oid = $request->get('oid');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->updateSurveyOptionQuestion($id, $oid, $value, $this->community->id);
    }

    public function editSurvey($slug, $surveyId,Request $request)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);

        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {

            $message = null;

            if ($val = $request->get('val')) {

                $validator = \Validator::make($val, [
                    'survey_title' => 'required|predefined|validalpha|min:3',
                    /* 'url' => 'required|predefined|min:3|alpha_dash|slug|unique:community_surveys,slug' */
                ]);
                if (! $validator->fails()) {
                    $survey = $this->communitySurveysRepository()->editSurvey($val, $survey, $this->community->id);

                    if ($survey) {
                        return redirect($this->community->present()->url('editsurvey').'/'.$survey->id);
                    } else {
                        $message = trans('formsurveys.url-already-taken-use-another-url');

                    }

                } else {
                    $message = $validator->messages()->first();
                }
            }

            $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);

            $categories = $this->community->categories;

            return $this->render('community.pannel.cms.surveys.edit-survey', ['survey' => $survey, 'message' => $message, 'categories' => $categories], [
                'title' => $this->setTitle(trans('formsurveys.manage-surveys')),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function surveyDataReport($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {

            // $questions=$this->communitySurveyQuestionsRepository()->getQuestions($surveyId,$this->community->id);

            $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($surveyId, $this->community->id);

            $mainQuestionIds = $questions->pluck('id')->all();
            $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestionsForQuestionIds($surveyId, $this->community->id, $mainQuestionIds);
            $subQuestionsByMainId = $subQuestions->groupBy('question_id');

            $allQuestions = $questions->concat($subQuestions);
            $choiceQuestionIds = $allQuestions->where('question_type', 'choice')->pluck('id')->all();
            $options = $this->communitySurveyQuestionOptionsRepository()->getByQuestionIds($choiceQuestionIds, $this->community->id);
            $optionsByQuestionId = $options->groupBy('question_id');

            $choiceCountsCacheKey = 'survey:choiceCounts:'.$this->community->id.':'.$surveyId;
            $choiceCountsByQuestionId = \Cache::remember($choiceCountsCacheKey, now()->addMinutes(5), function () use ($surveyId, $choiceQuestionIds) {
                return $this->communitySurveyAnswersRepository()->getChoiceCountsByQuestionIds($surveyId, $this->community->id, $choiceQuestionIds);
            });

            return $this->render('community.pannel.cms.surveys.survey-data-report', [
                'survey' => $survey,
                'questions' => $questions,
                'subQuestionsByMainId' => $subQuestionsByMainId,
                'optionsByQuestionId' => $optionsByQuestionId,
                'choiceCountsByQuestionId' => $choiceCountsByQuestionId,
            ], [
                'title' => $this->setTitle(trans('formsurveys.manage-surveys')),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function exportSurveyData($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        // $questions=$this->communitySurveyQuestionsRepository()->getQuestions($survey->id,$this->community->id);

        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {
            $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($surveyId, $this->community->id);

            $columnNames = [];
            foreach ($questions as $question) {
                if ($question->question_type != 'title') {
                    array_push($columnNames, trans($question->question));
                }

                if ($question->question_type == 'choice') {
                    $options = $this->communitySurveyQuestionOptionsRepository()->getByQuestionId($question->id);

                    if ($options) {
                        foreach ($options as $opt) {
                            $optQt = $this->communitySurveyQuestionsRepository()->getByOptionId($opt->id, $this->community->id);
                            if ($optQt) {
                                array_push($columnNames, trans($opt->option_title.'-'.$optQt->question));
                            }
                        }
                    }
                }

                $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestions($surveyId, $this->community->id, $question->id);

                if ($subQuestions) {
                    foreach ($subQuestions as $sbq) {
                        if ($sbq->question_type != 'title') {
                            array_push($columnNames, trans($sbq->question));
                        }
                    }
                }
            }

            $array_data[] = $columnNames;

            $datas = $this->communitySurveyAnswersRepository()->getAnswers($survey->id, $this->community->id);

            foreach ($datas as $data) {
                $dataCollected = [];

                foreach ($questions as $question) {
                    if ($question->question_type != 'title') {
                        $dataCollected = $this->getDataToExport($survey, $this->community, $question, $data, $dataCollected);
                    }

                    if ($question->question_type == 'choice') {
                        $options = $this->communitySurveyQuestionOptionsRepository()->getByQuestionId($question->id);
                        if ($options) {
                            foreach ($options as $opt) {
                                $optQt = $this->communitySurveyQuestionsRepository()->getByOptionId($opt->id, $this->community->id);
                                if ($optQt) {
                                    $dataCollected = $this->getDataToExport($survey, $this->community, $optQt, $data, $dataCollected);
                                }
                            }
                        }
                    }

                    $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestions($surveyId, $this->community->id, $question->id);

                    if ($subQuestions) {
                        foreach ($subQuestions as $sbq) {
                            if ($sbq->question_type != 'title') {
                                $dataCollected = $this->getDataToExport($survey, $this->community, $sbq, $data, $dataCollected);
                            }
                        }
                    }

                }
                $array_data[] = $dataCollected;
            }

            // return $array_data;
            $excelFileName = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $survey->title)));
            $this->exportAsExcel($array_data, $excelFileName);
        }

        return redirect($this->community->present()->url());
    }

    public function getDataToExport($survey, $community, $question, $data, $dataCollected)
    {
        $answer = $this->communitySurveyAnswersRepository()->getBySurveySubmit($survey->id, $community->id, $question->id, $data->submit_id);

        if ($answer) {
            if ($question->question_type == 'choice') {

                $multipleOptions = explode(',', $answer->answer);

                $ansrs = '';
                foreach ($multipleOptions as $opt) {
                    $option = $this->communitySurveyQuestionOptionsRepository()->getById($opt, $community->id);
                    if ($option) {
                        if ($ansrs != '') {
                            $ansrs = $ansrs.','.$option->option_title;
                        } else {
                            $ansrs = $option->option_title;
                        }
                    }
                }

                if ($question->multiple_option == 0) {
                    $mainQst = $this->communitySurveyQuestionsRepository()->getByOptionId($answer->answer, $community->id);
                    if ($mainQst) {

                        $subAnswer = $this->communitySurveyAnswersRepository()->getBySurveySubmit($survey->id, $community->id, $mainQst->id, $data->submit_id);

                        if ($subAnswer) {
                            $ansrs = $ansrs.' : '.$mainQst->question.' - '.$subAnswer->answer;
                        }

                    }
                }

                if ($ansrs) {
                    array_push($dataCollected, $ansrs);
                } else {
                    array_push($dataCollected, '');
                }
            } elseif ($question->question_type == 'rating') {
                array_push($dataCollected, $answer->answer.' star');
            } elseif ($question->question_type == 'file') {
                $fileUrl = $this->community->present()->getDocumentUrl($answer->answer);
                array_push($dataCollected, $fileUrl);
            } else {
                if ($answer->answer != '') {
                    array_push($dataCollected, $answer->answer);
                } else {
                    array_push($dataCollected, '');
                }
            }
        } else {
            array_push($dataCollected, '');
        }

        return $dataCollected;
    }

    public function exportSurveyResponse($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);

        $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($surveyId, $this->community->id);

        $columnNames = [];
        foreach ($questions as $question) {
            if ($question->question_type != 'title') {
                array_push($columnNames, trans($question->question));
            }

            $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestions($surveyId, $this->community->id, $question->id);

            if ($subQuestions) {
                foreach ($subQuestions as $sbq) {
                    if ($sbq->question_type != 'title') {
                        array_push($columnNames, trans($sbq->question));
                    }
                }
            }
        }

        array_push($columnNames, '');
        array_push($columnNames, '');
        array_push($columnNames, '');
        array_push($columnNames, 'Interesting');
        array_push($columnNames, 'Not Good');
        array_push($columnNames, 'Meet ASAP');

        $array_data[] = $columnNames;

        $datas = $this->communitySurveyAnswersRepository()->getAnswers($survey->id, $this->community->id);

        foreach ($datas as $data) {
            $dataCollected = [];

            foreach ($questions as $question) {
                if ($question->question_type != 'title') {
                    $dataCollected = $this->getDataToExport($survey, $this->community, $question, $data, $dataCollected);
                }

                $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestions($surveyId, $this->community->id, $question->id);

                if ($subQuestions) {
                    foreach ($subQuestions as $sbq) {
                        if ($sbq->question_type != 'title') {
                            $dataCollected = $this->getDataToExport($survey, $this->community, $sbq, $data, $dataCollected);
                        }
                    }
                }

            }

            $count1 = $this->communityFormsReportsRepository()->countResponse($data->submit_id, 1);
            $count2 = $this->communityFormsReportsRepository()->countResponse($data->submit_id, 2);
            $count3 = $this->communityFormsReportsRepository()->countResponse($data->submit_id, 3);

            array_push($dataCollected, '');
            array_push($dataCollected, '');
            array_push($dataCollected, '');
            array_push($dataCollected, $count1);
            array_push($dataCollected, $count2);
            array_push($dataCollected, $count3);

            $array_data[] = $dataCollected;
        }

        $excelFileName = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $survey->title))).'-response';
        $this->exportAsExcel($array_data, $excelFileName);
    }

    public function deletesurveyquestion(Request $request)
    {
        $id = $request->get('id');

        return $question = $this->communitySurveyQuestionsRepository()->deletesurveyquestion($id, $this->community->id);
    }

    public function copySurvey($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {
            $this->theme->share('settingPage', 'surveys');
            $this->communitySurveysRepository()->copySurvey($surveyId, $this->community->id);

            return redirect(\URL::previous());
        }

        return redirect($this->community->present()->url());
    }

    public function surveyDelete($slug, $surveyId)
    {
        $survey = $this->communitySurveysRepository()->getById($surveyId, $this->community->id);
        if ($survey and ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id)) {
            $this->theme->share('settingPage', 'surveys');
            $this->communitySurveysRepository()->surveyDelete($surveyId, $this->community->id);

            return redirect(\URL::previous());
        }

        return redirect($this->community->present()->url());
    }

    public function privilegeSettings(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = null;
        if ($val = $request->get('val')) {

            $save = $this->communityRepository()->saveExternalPrivilage($val, $this->community);
            if ($save) {
                \Session::flash('success', trans('community.pannel.information-updated-successfully'));

                $isCompleted = $this->communityRepository()->checkFieldsComplete($this->community->id);

                return redirect($this->community->present()->url('privilegesettings'));
                // $message = 'Information updated successfully.';
            } else {
                $message = trans('community.pannel.invalid-information');
            }

        }

        return $this->render('community.pannel.privilege-settings', ['fields' => $this->customFieldRepository()->listAll('community'), 'message' => $message], [
            'title' => $this->setTitle(trans('community.pannel.privilege-settings')),
        ]);
    }
	
	public function menuSettings(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $menus = [
            'connected_organization' => trans('global.connected-organization'),
            'my_website' => trans('global.my-website'),
            'stores' => trans('global.stores'),
            'my_social_profile' => trans('global.my-social-profile'),
            'my_calendar' => trans('global.my-calendar'),
            'notes' => trans('internal-collaborations.notes'),
            'invite_a_friend' => trans('global.invite-a-friend'),
            'job_dashboard' => trans('global.job-dashboard'),
            'marketplace' => $this->community ? $this->community->present()->marketplaceTitle() : trans('organizationsettings.eMarketplace'),
            'trends_mention' => trans('global.trends-mention'),
            'group_sync' => trans('community.pannel.app-marketplace'),
            'agreements' => trans('global.agreements'),
            'transactions' => trans('global.transactions'),
            'account_settings' => trans('global.account-settings'),
            'my_identity' => trans('global.my-identity'),
            'website_logo' => trans('global.website-logo'),
           // 'logout' => 'Logout',
        ];

        $message = null;
        if ($val = $request->get('val')) {
            $rules = [];
            foreach (array_keys($menus) as $key) {
                $rules['val.' . $key] = 'nullable|in:0,1';
            }

            $validator = \Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                $message = $validator->messages()->first();
            } else {
                $this->communitySocialMenuSettingsRepository()->saveSettings(
                    (int) $this->community->id,
                    (int) (\Auth::id() ?? 0),
                    (array) $val
                );
                \Session::flash('success', trans('cms.settings-saved-successfully'));
                return redirect($this->community->present()->url('menusettings'));
            }
        }
		
        $menuSettings = $this->communitySocialMenuSettingsRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.menu-settings', ['message' => $message, 'menus' => $menus, 'settings' => $menuSettings], [
            'title' => $this->setTitle(trans('community.pannel.menu-settings')),
        ]);
    }

    public function competitions()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $competitions = $this->communityCompetitionRepository()->getCompetition($this->community->id);

        return $this->render('community.pannel.cms.competitions.index', ['competitions' => $competitions], [
            'title' => $this->setTitle('Community Competitions'),
        ]);
    }

    public function addCompetition(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $message = '';
        if ($val = $request->get('val')) {

            $validator = \Validator::make($val, [
                'title' => 'required|predefined|validalpha|min:3',
            ]);
            if (! $validator->fails()) {
                $competition = $this->communityCompetitionRepository()->add($val, $this->community->id);

                if ($competition) {
                    return redirect($this->community->present()->url('competitions'));
                }

            } else {
                $message = $validator->messages()->first();
            }
        }

        $categories = $this->community->categories;

        return $this->render('community.pannel.cms.competitions.add', ['message' => $message, 'categories' => $categories], [
            'title' => $this->setTitle('Manage Surveys'),
        ]);
    }

    public function editCompetition($slug, $competitionId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $competition = $this->communityCompetitionRepository()->getById($competitionId, $this->community->id);

        if ($competition) {

            $message = null;

            if ($val = $request->get('val')) {

                $validator = \Validator::make($val, [
                    'title' => 'required|predefined|validalpha|min:3',
                ]);
                if (! $validator->fails()) {
                    $competition = $this->communityCompetitionRepository()->edit($val, $competition, $this->community->id);

                    if ($competition) {
                        return redirect($this->community->present()->url('editcompetition').'/'.$competition->id);
                    } else {
                        $message = 'URL already taken, use another URL.';

                    }

                } else {
                    $message = $validator->messages()->first();
                }
            }

            $competition = $this->communityCompetitionRepository()->getById($competitionId, $this->community->id);
            $categories = $this->community->categories;

            return $this->render('community.pannel.cms.competitions.edit', ['competition' => $competition, 'message' => $message, 'categories' => $categories], [
                'title' => $this->setTitle('Edit Competition'),
            ]);
        }
    }

    public function competitionToTopics()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $categories = $this->community->categories;

        return $this->render('community.pannel.cms.competitions.topics-setting', ['categories' => $categories], [
            'title' => $this->setTitle('Community Competitions'),
        ]);
    }

    public function setcompetitionToTopics(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $category_id = $request->get('category_id');
        $value = $request->get('value');

        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $category = $this->communityCategoryRepository()->get($category_id, $this->community->id);
        if ($category) {
            return $category = $this->communityCategoryRepository()->setCompetition($category, $value);
        }
    }

    public function disableCompetition(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $competition_id = $request->get('competition_id');
        $value = $request->get('value');

        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $competition = $this->communityCompetitionRepository()->getById($competition_id, $this->community->id);

        if ($competition) {
            return $competition = $this->communityCompetitionRepository()->disableCompetition($competition, $value);
        }
    }

    public function topicApplications()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $applications = $this->communityCategoryApplicationsRepository()->communityApplications($this->community->id);

        return $this->render('community.pannel.topics.applications', [
            'community' => $this->community,
            'applications' => $applications,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function centerApplications()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $applications = $this->communityCategoryApplicationsRepository()->communityCenterApplications($this->community->id);

        return $this->render('community.pannel.racing.center.applications', [
            'community' => $this->community,
            'applications' => $applications,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function topicApplicationStatus(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $id = $request->get('id');
        $value = $request->get('value');

        $application = $this->communityCategoryApplicationsRepository()->getById($this->community->id, $id);

        $code = 0;
        if ($application) {
            $status = $application->status;

            $applicationStatus = $this->communityCategoryApplicationsRepository()->topicApplicationStatus($this->community, $application, $value);

            if ($applicationStatus) {
                $code = 1;
                $status = $applicationStatus->status;
            }

            $newStatus = 0;
            if ($status == 1) {
                $newStatus = 1;
            }

            return json_encode([
                'code' => $code,
                'result' => $newStatus,
            ]);
        }
    }

    public function centerApplicationStatus(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $id = $request->get('id');
        $value = $request->get('value');

        $application = $this->communityCategoryApplicationsRepository()->getByRacingCommunityId($this->community->id, $id);

        $code = 0;
        if ($application) {
            $status = $application->status;

            $applicationStatus = $this->communityCategoryApplicationsRepository()->centerApplicationStatus($this->community, $application, $value);

            if ($applicationStatus) {
                $code = 1;
                $status = $applicationStatus->status;
            }

            $newStatus = 0;
            if ($status == 1) {
                $newStatus = 1;
            }

            return json_encode([
                'code' => $code,
                'result' => $newStatus,
            ]);
        }
    }

    public function deleteBannerImage(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $this->communityTopbannerRepository()->deleteBannerImage($this->community->id, $value);
    }

    public function updateSurveyQuestionAsDate(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $question = $this->communitySurveyQuestionsRepository()->updateSurveyQuestionAsDate($id, $value, $this->community->id);
    }

    public function copyWholeQuestion(Request $request)
    {
        $id = $request->get('id');
        $questionid = $request->get('questionid');

        $communityId = $this->community->id;

        $question_id = $this->communitySurveyQuestionsRepository()->copyWholeQuestion($id, $this->community->id);

        if ($question_id) {
            $options = '';
            $question = $this->communitySurveyQuestionsRepository()->getById($question_id, $communityId);

            $survey = $this->communitySurveysRepository()->getById($question->survey_id, $communityId);

            return (string) $this->theme->section('community.pannel.cms.surveys.generate-question', ['survey' => $survey, 'question' => $question, 'srNo' => $questionid]);
        }
    }

    public function copySubFormQuestion(Request $request)
    {
        $questionid = $request->get('id');
        $communityId = $this->community->id;

        $question_id = $this->communitySurveyQuestionsRepository()->copySubFormQuestion($questionid, $this->community->id);

        if ($question_id) {
            $options = '';
            $question = $this->communitySurveyQuestionsRepository()->getById($question_id, $communityId);

            $survey = $this->communitySurveysRepository()->getById($question->survey_id, $communityId);

            return (string) $this->theme->section('community.pannel.cms.surveys.generate-question', ['survey' => $survey, 'question' => $question, 'srNo' => '']);
        }
    }

    public function visitorsStat(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $chartType = (string) ($request->get('charttype') ?: 'bar');
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_stat_page_c' . $communityId . '_u' . $userId . '_ct' . $chartType . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        $start = new \DateTimeImmutable('-7 days');
        $dates = [];
        $dateValues = [];

        for ($i = 0; $i <= 7; $i++) {
            $dt = $start->modify('+' . $i . ' days');
            $dates[] = $dt->format('Y/m/d');
            $dateValues[] = $dt->format('Y-m-d');
        }

        $firstVisitCounts = $this->siteVisitorsDataRepository()->getCountsByValues($this->community->id, 'firstvisit', $dateValues);
        $pageViewCounts = $this->siteVisitorsDataRepository()->getCountsByValues($this->community->id, 'pageviews', $dateValues);

        $visitorsData = [];
        $pageViewData = [];

        if ($chartType == 'area') {
            foreach ($dates as $idx => $dt) {
                $visitingDate = $dateValues[$idx];

                $visitorsData[] = [
                    'date' => $dt,
                    'value' => (int) ($firstVisitCounts[$visitingDate] ?? 0),
                ];

                $pageViewData[] = [
                    'date' => $dt,
                    'value' => (int) ($pageViewCounts[$visitingDate] ?? 0),
                ];
            }
        } else {
            foreach ($dates as $idx => $dt) {
                $visitingDate = $dateValues[$idx];
                $label = (new \DateTimeImmutable($visitingDate))->format('j M Y');

                $visitorsData[] = [
                    'group_name' => trans('visitors.visitors'),
                    'name' => $label,
                    'value' => (int) ($firstVisitCounts[$visitingDate] ?? 0),
                ];
            }

            foreach ($dates as $idx => $dt) {
                $visitingDate = $dateValues[$idx];
                $label = (new \DateTimeImmutable($visitingDate))->format('j M Y');

                $visitorsData[] = [
                    'group_name' => trans('visitors.page-views'),
                    'name' => $label,
                    'value' => (int) ($pageViewCounts[$visitingDate] ?? 0),
                ];
            }
        }

        $pageViews = $this->siteVisitorsDataRepository()->pageViews($this->community->id);

        $summaryCounts = $this->siteVisitorsDataRepository()->getCountsByTypeValuePairs($this->community->id, [
            ['type' => 'unique_visitors', 'value' => 'unique_visitors'],
            ['type' => 'totalpageviews', 'value' => 'totalpageviews'],
            ['type' => 'visitingdates', 'value' => 'visitingdates'],
        ]);

        $uniqueVisitorsCount = (int) ($summaryCounts['unique_visitors']['unique_visitors'] ?? 0);
        $pageViewCount = (int) ($summaryCounts['totalpageviews']['totalpageviews'] ?? 0);
        $visitDates = (int) ($summaryCounts['visitingdates']['visitingdates'] ?? 0);

        $response = $this->render('community.pannel.visitors.index', [
            'community' => $this->community,
            'pageViews' => $pageViews,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'pageViewCount' => $pageViewCount,
            'visitorsData' => $visitorsData,
            'pageViewData' => $pageViewData,
            'visitDates' => $visitDates,
            'chartType' => $chartType,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorsGeographic(Request $request)
    {

        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $page = (int) $request->query('page', 1);
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_geo_page_c' . $communityId . '_u' . $userId . '_p' . $page . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        // $geographic=$this->siteVisitorsRepository()->geographic($this->community->id);
        // $uniqueVisitorsCount=$this->siteVisitorsRepository()->uniqueVisitorsCount($this->community->id);

        $summaryCounts = $this->siteVisitorsDataRepository()->getCountsByTypeValuePairs($this->community->id, [
            ['type' => 'allcountries', 'value' => 'allcountries'],
            ['type' => 'unique_visitors', 'value' => 'unique_visitors'],
        ]);

        $geographic = (int) ($summaryCounts['allcountries']['allcountries'] ?? 0);
        $uniqueVisitorsCount = (int) ($summaryCounts['unique_visitors']['unique_visitors'] ?? 0);

        // $geographicCountries=$this->siteVisitorsRepository()->geographicCountries($this->community->id);

        $geographicCountries = $this->siteVisitorsDataRepository()->geographicCountries($this->community->id);

        $geographicCountriesNames = $this->siteVisitorsDataRepository()->geographicCountriesNames($this->community->id);

        $response = $this->render('community.pannel.visitors.geographic', [
            'community' => $this->community,
            'geographic' => $geographic,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'geographicCountries' => $geographicCountries,
            'geographicCountriesNames' => $geographicCountriesNames,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorsPages(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $page = (int) $request->query('page', 1);
        $viewdate = (string) $request->get('viewdate');
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_pages_page_c' . $communityId . '_u' . $userId . '_p' . $page . '_d' . md5($viewdate) . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        if ($viewdate) {
            $pageViews = $this->siteVisitorsRepository()->visitorPagesDateWise($this->community->id, $viewdate);

            $visitingDate = date('Y-m-d', strtotime($viewdate));

            $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'firstvisit', $visitingDate);

            $pageViewCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'pageviews', $visitingDate);

        } else {
            $pageViews = $this->siteVisitorsDataRepository()->pageViews($this->community->id);

            $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'unique_visitors', 'unique_visitors');

            $pageViewCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'totalpageviews', 'totalpageviews');

        }

        $visitDates = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'visitingdates', 'visitingdates');

        $response = $this->render('community.pannel.visitors.pages', [
            'community' => $this->community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'visitDates' => $visitDates,
            'pageViewCount' => $pageViewCount,
            'pageViews' => $pageViews,
            'viewdate' => $viewdate,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorsUsers(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $viewdate = (string) $request->get('viewdate');
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_users_page_c' . $communityId . '_u' . $userId . '_d' . md5($viewdate) . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        if ($viewdate) {
            $visitingDate = date('Y-m-d', strtotime($viewdate));
        } else {
            $visitingDate = date('Y-m-d');
        }

        $pageViewCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'pageviews', $visitingDate);

        $users = $this->siteVisitorsRepository()->visitorsUsers($this->community->id, $visitingDate);

        $response = $this->render('community.pannel.visitors.users', [
            'community' => $this->community,
            'users' => $users,
            'viewdate' => $viewdate,
            'pageViewCount' => $pageViewCount,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorsEngagement(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_engagement_page_c' . $communityId . '_u' . $userId . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        // $engagementData=$this->siteVisitorsRepository()->engagementData($this->community->id);

        $engagementBuckets = $this->siteVisitorsDataRepository()->engagementBuckets($this->community->id);

        $response = $this->render('community.pannel.visitors.engagement', [
            'community' => $this->community,
            'engagementBuckets' => $engagementBuckets,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorsGeographicCities(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $page = (int) $request->query('page', 1);
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_geo_cities_page_c' . $communityId . '_u' . $userId . '_p' . $page . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        // $uniqueVisitorsCount=$this->siteVisitorsRepository()->uniqueVisitorsCount($this->community->id);

        $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'unique_visitors', 'unique_visitors');

        $geographicCities = $this->siteVisitorsDataRepository()->geographicCities($this->community->id);

        // $geographicCities=$this->siteVisitorsRepository()->geographicCities($this->community->id);

        $response = $this->render('community.pannel.visitors.geographic-cities', [
            'community' => $this->community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'geographicCities' => $geographicCities,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;
        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function visitorSystem(Request $request)
    {
        $communityId = (int) ($this->community->id ?? 0);
        $userId = (int) (auth()->check() ? auth()->id() : 0);
        $locale = (string) app()->getLocale();
        $cacheDriver = (string) config('cache.default');

        $pageCacheKey = 'vis_system_page_c' . $communityId . '_u' . $userId . '_l' . $locale;
        $cachedHtml = Cache::get($pageCacheKey);
        if (is_string($cachedHtml) && $cachedHtml !== '') {
            return response($cachedHtml)
                ->header('X-Stats-Cache', 'HIT')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        // $pageViewCount=$this->siteVisitorsRepository()->pageViewCount($this->community->id);

        $pageViewCount = $this->siteVisitorsDataRepository()->getCount($this->community->id, 'totalpageviews', 'totalpageviews');

        $browserData = $this->siteVisitorsDataRepository()->browserData($this->community->id);

        $response = $this->render('community.pannel.visitors.system', [
            'community' => $this->community,
            'pageViewCount' => $pageViewCount,
            'browserData' => $browserData,
        ], [
            'title' => $this->setTitle(''),
        ]);

        $stored = false;

        $htmlForResponse = null;

        try {
            $html = null;
            if (is_string($response)) {
                $html = $response;
            } elseif (is_object($response) && method_exists($response, 'getContent')) {
                $html = (string) $response->getContent();
            } elseif (is_object($response) && method_exists($response, 'render')) {
                $html = (string) $response->render();
            }

            if (is_string($html) && $html !== '') {
                $htmlForResponse = $html;
                $stored = Cache::put($pageCacheKey, $html, now()->addMinutes(5));
            }
        } catch (\Throwable $e) {
            // If caching fails, still return the live response.
        }

        $final = is_string($htmlForResponse) ? response($htmlForResponse) : (is_string($response) ? response($response) : $response);
        if (is_object($final) && method_exists($final, 'header')) {
            $final->header('X-Stats-Cache', $stored ? 'MISS-STORE' : 'MISS')
                ->header('X-Cache-Driver', $cacheDriver);
        }

        return $final;
    }

    public function assignSurveyGroup(Request $request)
    {
        $surveyId = $request->get('id');
        $val = $request->get('val');

        if ($this->community->present()->canManage()) {
            $form = $this->communitySurveysRepository()->assignSurveyGroup($surveyId, $this->community->id, $val);
        }
    }

    public function surveyReportsData($slug, $surveyId,Request $request)
    {
        $type = $request->get('type');

        $survey = $this->communitySurveysRepository()->getByIdComId($surveyId, $this->community->id);
        if ($this->community->present()->isAdminSubAdmin() || $survey->user_id == \Auth::user()->id) {
            $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($survey->id, $this->community->id);

            $datas = $this->communitySurveyAnswersRepository()->getAnswersList($survey->id, $this->community->id);

            $mainQuestionIds = $questions->pluck('id')->all();
            $subQuestions = $this->communitySurveyQuestionsRepository()->getSubQuestionsForQuestionIds($survey->id, $this->community->id, $mainQuestionIds);
            $subQuestionsByMainId = $subQuestions->groupBy('question_id');
            $questionsWithSubs = $questions->concat($subQuestions);

            $submitIds = [];
            if (is_object($datas) && method_exists($datas, 'getCollection')) {
                $submitIds = $datas->getCollection()->pluck('submit_id')->filter()->unique()->values()->all();
            } elseif (is_iterable($datas)) {
                $submitIds = collect($datas)->pluck('submit_id')->filter()->unique()->values()->all();
            }

            $questionIdsForPage = $questionsWithSubs->pluck('id')->all();
            $answerRows = $this->communitySurveyAnswersRepository()->getAnswersBySubmitIdsAndQuestionIds($survey->id, $this->community->id, $submitIds, $questionIdsForPage);

            $rawBySubmitAndQuestion = [];
            foreach ($answerRows as $row) {
                $rawBySubmitAndQuestion[$row->submit_id][$row->question_id] = $row->answer;
            }

            $choiceQuestionIds = $questionsWithSubs->where('question_type', 'choice')->pluck('id')->all();
            $options = $this->communitySurveyQuestionOptionsRepository()->getByQuestionIds($choiceQuestionIds, $this->community->id);
            $optionTitleById = [];
            foreach ($options as $opt) {
                $optionTitleById[$opt->id] = $opt->option_title;
            }

            $optionIdsUsed = [];
            foreach ($answerRows as $row) {
                if (! in_array($row->question_id, $choiceQuestionIds)) {
                    continue;
                }
                $parts = explode(',', (string) $row->answer);
                foreach ($parts as $part) {
                    $part = trim($part);
                    if ($part !== '') {
                        $optionIdsUsed[] = $part;
                    }
                }
            }
            $optionIdsUsed = array_values(array_unique($optionIdsUsed));

            $followupQuestions = $this->communitySurveyQuestionsRepository()->getByOptionIds($optionIdsUsed, $this->community->id);
            $followupByOptionId = $followupQuestions->keyBy('option_id');
            $followupQuestionIds = $followupQuestions->pluck('id')->all();
            if (! empty($followupQuestionIds) && ! empty($submitIds)) {
                $followupAnswerRows = $this->communitySurveyAnswersRepository()->getAnswersBySubmitIdsAndQuestionIds($survey->id, $this->community->id, $submitIds, $followupQuestionIds);
                foreach ($followupAnswerRows as $row) {
                    $rawBySubmitAndQuestion[$row->submit_id][$row->question_id] = $row->answer;
                }
            }

            $formattedBySubmitAndQuestion = [];
            foreach ($submitIds as $submitId) {
                foreach ($questionsWithSubs as $question) {
                    $qid = $question->id;
                    $raw = $rawBySubmitAndQuestion[$submitId][$qid] ?? null;
                    if (is_null($raw) || (string) $raw === '') {
                        $formattedBySubmitAndQuestion[$submitId][$qid] = '';
                        continue;
                    }

                    if ($question->question_type == 'choice') {
                        $multipleOptions = explode(',', (string) $raw);
                        $ansrs = '';
                        foreach ($multipleOptions as $optId) {
                            $optId = trim($optId);
                            if ($optId === '') {
                                continue;
                            }
                            $title = $optionTitleById[$optId] ?? null;
                            if (! $title) {
                                continue;
                            }
                            if ($ansrs != '') {
                                $ansrs = $ansrs.','.$title;
                            } else {
                                $ansrs = $title;
                            }
                        }

                        if ((int) $question->multiple_option === 0) {
                            $singleOptId = trim((string) $raw);
                            $mainQst = $followupByOptionId->get($singleOptId);
                            if ($mainQst) {
                                $subRaw = $rawBySubmitAndQuestion[$submitId][$mainQst->id] ?? null;
                                if (! is_null($subRaw) && (string) $subRaw !== '') {
                                    $ansrs = $ansrs.' : '.$mainQst->question.' - '.$subRaw;
                                }
                            }
                        }

                        $formattedBySubmitAndQuestion[$submitId][$qid] = $ansrs ?: '';
                    } elseif ($question->question_type == 'rating') {
                        $formattedBySubmitAndQuestion[$submitId][$qid] = $raw.' star';
                    } elseif ($question->question_type == 'file') {
                        $formattedBySubmitAndQuestion[$submitId][$qid] = $this->community->present()->getDocumentUrl($raw);
                    } else {
                        $formattedBySubmitAndQuestion[$submitId][$qid] = (string) $raw;
                    }
                }
            }

            $reportsBySubmitId = [];
            if (! empty($submitIds) && \Auth::check()) {
                $reports = $this->communityFormsReportsRepository()->getByUserSubmitIds($submitIds, \Auth::user()->id);
                foreach ($reports as $report) {
                    $reportsBySubmitId[$report->submit_id] = $report;
                }
            }

            return $this->render('community.pannel.cms.surveys.survey-data', [
                'survey' => $survey,
                'datas' => $datas,
                'questions' => $questions,
                'type' => $type,
                'subQuestionsByMainId' => $subQuestionsByMainId,
                'answersBySubmitAndQuestion' => $formattedBySubmitAndQuestion,
                'reportsBySubmitId' => $reportsBySubmitId,
            ], [
                'title' => $this->setTitle(trans('formsurveys.surveys-reports')),
            ]);
        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function uploadSurveyMedia(Request $request)
    {
        $val = $request->get('val');

        $question = $this->communitySurveyQuestionsRepository()->uploadSurveyMedia($val, $this->community);

        if ($question) {
            return (string) $this->theme->section('community.pannel.cms.surveys.question-media', ['community' => $this->community, 'question' => $question]);
        } else {
            return 0;
        }
    }

    public function useSurveyQuestionMedia(Request $request)
    {
        $id = $request->get('id');
        $val = $request->get('val');

        return $question = $this->communitySurveyQuestionsRepository()->useSurveyQuestionMedia($id, $val, $this->community->id);
    }

    public function assignSurveyGroupAdmin(Request $request)
    {
        $surveyId = $request->get('id');
        $val = $request->get('value');
        $group_id = $request->get('group_id');

        if ($this->community->present()->canManage()) {
            return $this->communitySurveysRepository()->assignSurveyGroupAdmin($surveyId, $this->community->id, $val, $group_id);
        }
    }

    public function draftEmails(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;
        $message = '';
        if ($val = $request->get('val')) {

            $community = $this->communityRepository()->draftEmails($val, $this->community);

            $message = 'Emails saved succefully';
        }

        return $this->render('community.pannel.ownemails.draft-emails', ['community' => $community, 'message' => $message], [
            'title' => $this->setTitle('Draft Emails'),
        ]);
    }

    public function emailSignature(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;
        $message = '';
        if ($val = $request->get('val')) {

            $community = $this->communityRepository()->emailSignature($val, $this->community);

            $message = 'Email saved succefully';
        }

        return $this->render('community.pannel.ownemails.signature-email', ['community' => $community, 'message' => $message], [
            'title' => $this->setTitle('Signature Email'),
        ]);
    }

    public function fromEmailVerify(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;
        $message = '';

        $awsAccessKeyId = config('amazon-id');
        $awsSecretKey = config('amazon-access-key');
        $region = 'us-east-1';

        if (! class_exists(SesClient::class)) {
            \Log::error('AWS SES client class is missing (Aws\\Ses\\SesClient). Email verification cannot run.');
            $message = 'Email verification is temporarily unavailable. Please try again later.';

            return $this->render('community.pannel.ownemails.email-verification', ['community' => $community, 'message' => $message], [
                'title' => $this->setTitle('Email Verification'),
            ]);
        }

        $SesClient = new SesClient([
            'version' => 'latest',
            'region' => $region,
            'credentials' => [
                'key' => $awsAccessKeyId,
                'secret' => $awsSecretKey,
            ],
        ]);

        $template_name = 'Community_Email_Verification';

        /*$html_body = "<h1>Ready to start sending email with your own email address</h1>
                        <p>We are happy to have you on
                          board! There's just one last step to complete before
                          you can start sending email. Just click the following
                          link to verify your email address. Once we confirm that
                          you're really you, we'll give you some additional
                          information to help you get started with your own email.</p>";

        $subject = 'Please confirm your email address';

        try {
            $result = $SesClient->CreateCustomVerificationEmailTemplate([
                'TemplateName' => $template_name,
                'FromEmailAddress' => 'no-reply@idhubs.com',
                'TemplateSubject' => $subject,
                'TemplateContent'=>$html_body,
                'SuccessRedirectionURL'=>'https://idhubs.com/',
                'FailureRedirectionURL'=>'https://idhubs.com/',
            ]);
            var_dump($result);
        } catch (AwsException $e) {
            return $e;
        }*/

        /*try {
            $result = $SesClient->UpdateCustomVerificationEmailTemplate([
                'TemplateName' => $template_name,
                'TemplateContent' => config('site_email'),
            ]);
            var_dump($result);
        } catch (AwsException $e) {
            return $e;
        }
        exit;	*/

        if ($community->send_email_from and $community->own_email_verified == 0) {
            $email_address = $community->send_email_from;
            try {
                $result = $SesClient->getIdentityVerificationAttributes([
                    'Identities' => [$email_address],
                ]);

                if ($result['VerificationAttributes'][$email_address]['VerificationStatus'] == 'Success') {
                    $community->own_email_verified = 1;
                    $community->send_email_from_own = 1;
                    $community->save();

                    return redirect($this->community->present()->url('fromemailverify'));
                }
            } catch (\Throwable $e) {
                // return $e;
            }
        }

        if ($email_address = $request->get('email_address') and $community->own_email_verified == 0) {

            $community->send_email_from = $email_address;
            $community->save();

            $base_url = \URL();
            if ($base_url == 'http://idhubsnew.devs') {
                $SuccessRedirectionURL = 'https://idhubs.com';
                $FailureRedirectionURL = 'https://idhubs.com';
            } else {
                $SuccessRedirectionURL = $community->present()->url('emailverificationsuccess');
                $FailureRedirectionURL = $community->present()->url('emailverificationfailed');
            }

            try {
                $result = $SesClient->UpdateCustomVerificationEmailTemplate([
                    'TemplateName' => $template_name,
                    'SuccessRedirectionURL' => $SuccessRedirectionURL,
                    'FailureRedirectionURL' => $FailureRedirectionURL,
                    'FromEmailAddress' => config('site_email'),
                ]);

            } catch (\Throwable $e) {
                // return $e;
            }

            try {
                /*$result = $SesClient->verifyEmailIdentity([
                    'EmailAddress' => $email_address,
                ]);*/

                $result = $SesClient->sendCustomVerificationEmail([
                    'EmailAddress' => $email_address,
                    'TemplateName' => $template_name,
                ]);

                $message = 'Check your email and click on the link to verify your email address.';
                \Session::flash('message', $message);

                return redirect($this->community->present()->url('fromemailverify'));
            } catch (\Throwable $e) {
                $message = 'Something went wrong, try again later';
                \Session::flash('message', $message);

                return redirect($this->community->present()->url('fromemailverify'));
            }
        }

        return $this->render('community.pannel.ownemails.email-verification', ['community' => $community, 'message' => $message], [
            'title' => $this->setTitle('Email Verification'),
        ]);
    }

    public function sendFromOwnEmail(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $value = $request->get('value');
        $community = $this->community;
        $community->send_email_from_own = $value;
        $community->save();
    }

    public function primaryApplications()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $applications = $this->communityPrimaryMembersRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.primary-applications', ['applications' => $applications], [
            'title' => $this->setTitle('Draft Emails'),
        ]);
    }

    public function changePrimaryAplsts(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $id = $request->get('id');
        $value = $request->get('value');

        $application = $this->communityPrimaryMembersRepository()->changePrimaryAplsts($id, $value);
    }

    public function useTemplate($community_id, $templateId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $msg = '';

        if ($val = $request->get('val')) {

            $hasSent = $this->communityCampaignEmailsRepository()->sendEmailTemplate($val, $this->community);

            if ($hasSent) {
                $msg = str_pad($hasSent, 2, '0', STR_PAD_LEFT).' emails sent';
            } else {
                $msg = 'Select target category to proceed.';
            }

            // return redirect(\URL::previous());
        }

        $categories = $this->communityCampaignMailingCategoryRepository()->getAllByCommunityId($this->community->id);

        $templates = $this->communityCampaignTemplatesRepository()->getAllByCommunityId($this->community->id);

        $template = $this->communityCampaignTemplatesRepository()->getByIdComId($templateId, $this->community->id);

        $listAllSubjects = $this->communityCampaignEmailsRepository()->campaignSubjects($this->community->id, $templateId);

        return $this->render('community.pannel.campaigns.template.use-template', ['categories' => $categories, 'templates' => $templates, 'template' => $template, 'msg' => $msg, 'listAllSubjects' => $listAllSubjects],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function sendCampaign($community_id, $campaignId,Request $request)
    {

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $msg = '';

        if ($val = $request->get('val')) {

            $hasSent = $this->communityCampaignEmailsRepository()->sendEmailTemplate($val, $this->community);

            $status = 1;
            $sending = 0;
            $dataId = 0;
            if ($hasSent === 'category') {
                $status = 0;
                $msg = trans('campaign.select-target-category-to-proceed');
            } elseif ($hasSent === 'limit') {
                $status = 0;
                $msg = trans('campaign.daily-email-limit-used', ['limit' => config('campaign-email-limit-daily')]);
            } else {
                $status = 1;
                $dataId = $hasSent;
                $msg = trans('campaign.sending');
                $sending = 0;
            }

            return json_encode([
                'status' => $status,
                'message' => $msg,
                'dataId' => $dataId,
                'sending' => $this->communityCampaignEmailsSentRepository()->getUnsentCount($dataId),
            ]);
            // return redirect(\URL::previous());
        }

        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);

        $categories = $this->communityCampaignMailingCategoryRepository()->getAllByCommunityId($this->community->id);

        $smtp_details = $this->userSettingsRepository()->getByUserId();

        return $this->render('community.pannel.campaigns.send-campaign', ['categories' => $categories, 'campaign' => $campaign, 'msg' => $msg, 'smtp_details' => $smtp_details],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function campaignReport($community_id, $campaignId,Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);
        // $records=$this->communityCampaignEmailsRepository()->getByCommunityIdCampaign($this->community->id,$campaignId);

        $categories = $this->communityCampaignEmailsRepository()->getCampaignCategories($this->community->id, $campaignId);

        $allCategories = [];

        if ($categories) {
            foreach ($categories as $category) {
                $expCat = explode(',', $category);

                foreach ($expCat as $cat) {
                    if (! in_array($cat, $allCategories)) {
                        array_push($allCategories, $cat);
                    }
                }
            }
        }

        $catList = '';
        if ($allCategories) {
            $catList = $this->communityCampaignMailingCategoryRepository()->getByIds($allCategories);
        }

        $type = $request->get('type');

        $records = $this->communityCampaignEmailsSentRepository()->getByCommunityCampaignIdCat($this->community->id, $campaignId, $type);

        return $this->render('community.pannel.campaigns.campaign-report', ['campaign' => $campaign, 'records' => $records, 'catList' => $catList, 'type' => $type],
            ['title' => $this->setTitle(trans('campaign.report'))]
        );
    }

    public function campaignProspects($community_id, Request $request, $campaignId = null)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        // Default to the first available campaign when none is selected.
        // Use the same list/filters as /c/{id}/campaigns.
        $campaigns = $this->communityCampaignRepository()->getByCommunityIdProspects($this->community->id);
        $campaigns = collect($campaigns)->sort(function ($a, $b) {
            $aTitle = trim((string) ($a->title ?? ''));
            $bTitle = trim((string) ($b->title ?? ''));
            return strnatcasecmp($aTitle, $bTitle);
        })->values();

        if (empty($campaignId)) {
            $firstCampaignId = null;
            if ($campaigns) {
                foreach ($campaigns as $camp) {
                    if (!empty($camp->id)) {
                        $firstCampaignId = $camp->id;
                        break;
                    }
                }
            }

            if (!empty($firstCampaignId)) {
                return redirect($this->community->present()->url('prospects').'/'.$firstCampaignId);
            }
        }

        $campaign = null;
        $catList = '';
        $type = $request->get('type');
        $records = [];

        if (!empty($campaignId)) {
            $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);

            $categories = $this->communityCampaignEmailsRepository()->getCampaignCategories($this->community->id, $campaignId);
            $allCategories = [];
            if ($categories) {
                foreach ($categories as $category) {
                    $expCat = explode(',', $category);
                    foreach ($expCat as $cat) {
                        if (!in_array($cat, $allCategories)) {
                            array_push($allCategories, $cat);
                        }
                    }
                }
            }

            if ($allCategories) {
                $catList = $this->communityCampaignMailingCategoryRepository()->getByIds($allCategories);
            }

            $records = $this->communityCampaignEmailsSentRepository()->getProspectsByCommunityCampaignIdCat($this->community->id, $campaignId, $type);
        }

        return $this->render('community.pannel.campaigns.prospects', [
            'campaign' => $campaign,
            'campaigns' => $campaigns,
            'records' => $records,
            'catList' => $catList,
            'type' => $type,
        ], [
            'title' => $this->setTitle(trans('internal-collaborations.prospects')),
        ]);
    }

    public function setProspectLead($community_id, Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return response()->json(['status' => 0, 'message' => 'Unauthorized'], 403);
        }

        $recordId = (int) $request->get('id');
        $isLead = (int) $request->get('is_lead');
        $isLead = $isLead ? 1 : 0;

        if ($recordId <= 0) {
            return response()->json(['status' => 0, 'message' => 'Invalid record'], 422);
        }

        $updated = $this->communityCampaignEmailsSentRepository()->setIsLeadByRecordId($this->community->id, $recordId, $isLead);

        return response()->json([
            'status' => $updated ? 1 : 0,
        ]);
    }

    public function qualifiedLeads($community_id, Request $request, $campaignId = null)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        // Default to the first available campaign when none is selected.
        // Use the same list/filters as /c/{id}/campaigns.
        $campaigns = $this->communityCampaignRepository()->getByCommunityIdProspects($this->community->id);
        $campaigns = collect($campaigns)->sort(function ($a, $b) {
            $aTitle = trim((string) ($a->title ?? ''));
            $bTitle = trim((string) ($b->title ?? ''));
            return strnatcasecmp($aTitle, $bTitle);
        })->values();

        if (empty($campaignId)) {
            $firstCampaignId = null;
            if ($campaigns) {
                foreach ($campaigns as $camp) {
                    if (!empty($camp->id)) {
                        $firstCampaignId = $camp->id;
                        break;
                    }
                }
            }

            if (!empty($firstCampaignId)) {
                return redirect($this->community->present()->url('qualifiedleads').'/'.$firstCampaignId);
            }
        }

        $campaign = null;
        $records = [];

        if (!empty($campaignId)) {
            $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);
            $records = $this->communityCampaignEmailsSentRepository()->getQualifiedLeadsByCommunityCampaignId($this->community->id, $campaignId);
        }

        return $this->render('community.pannel.campaigns.qualified-leads', [
            'records' => $records,
            'campaign' => $campaign,
            'campaigns' => $campaigns,
        ], [
            'title' => $this->setTitle(trans('internal-collaborations.qualified-lead')),
        ]);
    }

    public function campaignDelete($community_id, $campaignId,Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);

        if ($campaign) {
            $campaign->status = 0;
            $campaign->save();
        }

        return redirect(\URL::previous());
    }

    public function useCampaignTemplate($community_id, $templateId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $msg = '';

        if ($val = $request->get('val')) {
            $createEmail = $this->communityCampaignRepository()->createEmailCampaign($val, $this->community);

            return redirect($this->community->present()->url('campaigns'));
        }

        $categories = $this->communityCampaignMailingCategoryRepository()->getAllByCommunityId($this->community->id);

        $templates = $this->communityCampaignTemplatesRepository()->getAllByCommunityId($this->community->id);

        $template = $this->communityCampaignTemplatesRepository()->getByIdComId($templateId, $this->community->id);

        $listCampaign = $this->communityCampaignRepository()->campaignSubjects($this->community->id, $templateId);

        return $this->render('community.pannel.campaigns.template.use-template-subject', ['categories' => $categories, 'templates' => $templates, 'template' => $template, 'msg' => $msg, 'listCampaign' => $listCampaign],
            ['title' => $this->setTitle('Members')]
        );
    }

    public function templateStatistics(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $yearMonths = [];

        $sentCampaigs = [];
        $createdCampaigns = [];
        for ($m = 1; $m <= 12; $m++) {
            $month = date('Y-m', mktime(0, 0, 0, $m, 1, date('Y')));
            // array_push($yearMonths,$month);

            $sentByMonth = $this->communityCampaignEmailsSentRepository()->getSentByYearMonth($this->community->id, $month);
            array_push($sentCampaigs, $sentByMonth);

            $createdByMonth = $this->communityCampaignRepository()->getSentByYearMonth($this->community->id, $month);
            array_push($createdCampaigns, $createdByMonth);
        }

        $crCmapigns = implode(',', $createdCampaigns);
        $stCmapigns = implode(',', $sentCampaigs);

        $templateCount = $this->communityCampaignTemplatesRepository()->getByCommunityIdCnt($this->community->id);
        $campaignCount = $this->communityCampaignRepository()->getByCommunityIdCnt($this->community->id);
        $emailIdsCount = $this->communityMembersEmailsRepository()->getByCommunityIdCnt($this->community->id);
        $campaignSentCount = $this->communityCampaignEmailsRepository()->campaignSentCount($this->community->id);
        $emailSentCount = $this->communityCampaignEmailsSentRepository()->emailSentCount($this->community->id);
        $emailCategoriesCount = $this->communityCampaignMailingCategoryRepository()->getByCommunityIdCount($this->community->id);

        return $this->render('community.pannel.campaigns.template.statistics',
            ['templateCount' => $templateCount,
                'campaignCount' => $campaignCount,
                'emailIdsCount' => $emailIdsCount,
                'emailSentCount' => $emailSentCount,
                'campaignSentCount' => $campaignSentCount,
                'crCmapigns' => $crCmapigns,
                'stCmapigns' => $stCmapigns,
                'emailCategoriesCount' => $emailCategoriesCount,
            ],
            ['title' => $this->setTitle(trans('campaign.campaign-statistics'))]
        );
    }

    public function smtpDetails(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $smtp_details = $this->userSettingsRepository()->getByUserId();

        $message = '';
        if ($val = $request->get('val')) {
            $smtp_details = $this->userSettingsRepository()->add($val);
            $message = trans('campaign.details-saved-successfully');
        }

        return $this->render('community.pannel.campaigns.smtp-details',
            [
                'smtp_details' => $smtp_details,
                'message' => $message,
            ],
            ['title' => $this->setTitle(trans('campaign.smtp-details'))]
        );
    }

    public function getEmailsByCat(Request $request)
    {
        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $category_id = $request->get('category_id');
        $campaign_id = $request->get('id');

        $emails = $this->communityMembersEmailsRepository()->getAllCampaignEmailByCat($category_id, $this->community->id);

        return (string) $this->theme->section('community.pannel.campaigns.template.category-emails', ['community' => $this->community, 'emails' => $emails, 'campaign_id' => $campaign_id]);
    }

    public function templateFooter(Request $request)
    {
        // if (!($this->community->present()->isAdminSubAdmin())) redirect('home')->send();

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');

        $footer = $this->communityCampaignTemplatesFooterRepository()->getByCommunityId($this->community->id);

        return $this->render('community.pannel.campaigns.template.footer', ['footer' => $footer], [
            'title' => $this->setTitle('Campaigns'),
        ]);
    }

    public function saveTemplateFooter(Request $request)
    {
        // if (!($this->community->present()->isAdminSubAdmin())) redirect('home')->send();

        if ($this->community->present()->canDoCampaign() == 0) {
            return false;
        }

        $pagename = $request->get('pagename');

        $template = $this->communityCampaignTemplatesFooterRepository()->saveFooter($pagename, $this->community);

        return $this->community->present()->url('campaigntemplates');
    }

    public function campaignReportData(Request $request)
    {
        $id = $request->get('id');

        $record = $this->communityCampaignEmailsSentRepository()->getById($id);

        return (string) $this->theme->section('community.pannel.campaigns.note-data', ['record' => $record]);
    }

    public function saveRecordNote(Request $request)
    {
        $id = $request->get('id');
        $note = $request->get('note');
        $campaign_id = $request->get('campaign_id');
        $record = $this->communityCampaignEmailsSentRepository()->saveRecordNote($id, $note, $campaign_id);
    }

    public function allCampaignsData()
    {
        // if (!($this->community->present()->isAdminSubAdmin())) redirect('home')->send();

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $campaigns = $this->communityCampaignRepository()->getByCommunityIdAll($this->community->id);

        return $this->render('community.pannel.campaigns.campaigns-data', ['campaigns' => $campaigns], [
            'title' => $this->setTitle('campaigns'),
        ]);
    }

    public function allCampaignsReport()
    {
        // if (!($this->community->present()->isAdminSubAdmin())) redirect('home')->send();

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $campaigns = $this->communityCampaignRepository()->getByCommunityIdAll($this->community->id);

        return $this->render('community.pannel.campaigns.all-campaigns-report', ['campaigns' => $campaigns], [
            'title' => $this->setTitle('campaigns'),
        ]);
    }

    public function campaignData($slug, $campaign_id)
    {
        // if (!($this->community->present()->isAdminSubAdmin())) redirect('home')->send();

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $this->theme->share('settingPage', 'campaigns');
        $campaign = $this->communityCampaignRepository()->getByIdComId($campaign_id, $this->community->id);

        return $this->render('community.pannel.campaigns.campaigns-data-report', ['campaign' => $campaign], [
            'title' => $this->setTitle('campaigns'),
        ]);
    }

    public function activeLanguages()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $communityId = (int) $this->community->id;

        // Show all globally activated languages (AdminCP -> Languages) without requiring
        // the community owner to "add" them first. Merge with community-specific settings.
        $globalActiveLanguages = $this->languageRepository()->getActiveall();
        $communityLanguages = $this->communityLanguagesRepository()->getByCommunityIdAll($communityId);
        $communityByVar = [];
        foreach ($communityLanguages as $cl) {
            if (!empty($cl->var)) {
                $communityByVar[(string) $cl->var] = $cl;
            }
        }

        $rows = [];

        // Always display English.
        $enRow = (object) [
            'var' => 'en',
            'active' => 1,
            'exists_in_community' => isset($communityByVar['en']),
        ];
        $rows[] = $enRow;

        foreach ($globalActiveLanguages as $gl) {
            $var = (string) ($gl->var ?? '');
            if ($var === '' || strtolower($var) === 'en') {
                continue;
            }

            $cl = $communityByVar[$var] ?? null;
            $rows[] = (object) [
                'var' => $var,
                'active' => (int) ($cl->active ?? 0),
                'exists_in_community' => (bool) $cl,
            ];
        }

        $languages = collect($rows);

        return $this->render('community.pannel.languages.list', ['languages' => $languages], [
            'title' => $this->setTitle('Languages'),
        ]);
    }

    public function addlanguage($slug, $var)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $this->communityLanguagesTranslationRepository()->addLanguage($var, $this->community);
        // return redirect(\URL::previous());
    }

    public function activateLanguage($slug, $var)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $this->communityLanguagesRepository()->activateLanguage($var, $this->community->id);

        return redirect(\URL::previous());
    }

    public function deactivateLanguage($slug, $var)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $this->communityLanguagesRepository()->deactivateLanguage($var, $this->community->id);

        return redirect(\URL::previous());
    }

    public function setDefaultLanguage($slug, $var)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        // Default language is no longer managed at community-level.
        \Session::flash('error', 'Default language is now chosen by user.');
        return redirect(\URL::previous());
    }

    public function removeDefaultLanguage($slug, $var)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        // Default language is no longer managed at community-level.
        \Session::flash('error', 'Default language is now chosen by user.');
        return redirect(\URL::previous());
    }

    public function updateLanguage($slug, $var,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $languages = $this->communityLanguagesRepository()->getByCommunityIdAll($this->community->id);

        if ($val = $request->get('val')) {

            $this->communityLanguagesTranslationRepository()->updateLanguages($val, $this->community->id);
        }

        $phrases = $this->communityLanguagesTranslationRepository()->getByCommunityVar($this->community->id, $var);

        $selectedLang = $this->languageRepository()->findByVar($var);

        return $this->render('community.pannel.languages.update-phrase', ['languages' => $languages, 'phrases' => $phrases, 'selectedLang' => $selectedLang], [
            'title' => $this->setTitle('Languages'),
        ]);
    }

    public function addPg(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $theme_id = $request->get('use_theme_id');
        $selected_theme = '';
        if ($theme_id) {
            $selected_theme = $this->themesRepository()->getById($theme_id);
        }

        $this->theme->share('settingPage', 'pages');
        $pagesmenus = $this->communityPagesRepository()->getAllPublishedMenusByCommunityId($this->community->id);

        return $this->render('community.pannel.cms.pages.add-page', ['pagesmenus' => $pagesmenus, 'page' => '', 'selected_theme' => $selected_theme, 'theme_id' => $theme_id], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function savePage(Request $request)
    {
        $page_title = $request->get('page_title');
        $pagename = $request->get('pagename');
        $show_page_as_menu = $request->get('show_page_as_menu');
        $menu_id = $request->get('menu_id');
        $show_website_footer = $request->get('show_website_footer');
        $page_id = $request->get('page_id');
        $page_slug = $request->get('page_slug');
        $pagehtml = $request->get('pagehtml');
        $menu_srno = $request->get('menu_srno');
		$show_default_header = $request->get('show_default_header');

        $page = $this->communityPagesRepository()->savePage($page_title, $pagename, $show_page_as_menu, $menu_id, $show_website_footer, $page_id, $this->community, $page_slug, $pagehtml, $menu_srno,$show_default_header);

        return $this->community->present()->url('editpg/'.$page->id.'?vieweditor=editor');
    }
	
	public function savePageHeader(Request $request)
    {
        $page_slug = $request->get('page_slug');
        $pagehtml = $request->get('pagehtml');
		$show_default_header = $request->get('show_default_header');
		$reset_header = $request->get('reset_header');
        
		$page = $this->communityPagesRepository()->savePageHeader($page_slug, $pagehtml, $this->community,$show_default_header,$reset_header);

        return $this->community->present()->url('editpageheader/'.$page_slug.'?vieweditor=editor');
    }

    public function editPg($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');
        $pagesmenus = $this->communityPagesRepository()->getAllPublishedMenusByCommunityId($this->community->id);
        $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);

        return $this->render('community.pannel.cms.pages.edit-page', ['pagesmenus' => $pagesmenus, 'page' => $page], [
            'title' => $this->setTitle(trans('cms.pages')),
        ]);
    }
	
	public function editPageHeader($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pagesheaders');
        $page = $this->communityPagesRepository()->getByIdComIdHeaderPage($pageId, $this->community->id);

		$slug=$pageId;
        return $this->render('community.pannel.cms.pages.edit-header-page', ['page' => $page,'slug'=>$slug], [
            'title' => $this->setTitle(trans('cms.page-header')),
        ]);
    }

	public function editPageHeaderPreview($slug, $pageId, Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $homecontents = $this->community->present()->getHomeContents();
        $pages = $this->community->present()->getPages();
        $feviconImage = $this->community->present()->getFeviconAvatar();

        $page_header = $this->communityPagesRepository()->getByIdComIdHeaderPage($pageId, $this->community->id);

        return response()
            ->view('themes.frontend.default.views.community.pannel.cms.pages.page-header-preview-iframe', [
                'community' => $this->community,
                'homecontents' => $homecontents,
                'pages' => $pages,
                'feviconImage' => $feviconImage,
                'page_header' => $page_header,
                'header_slug' => $pageId,
            ])
            ->header('X-Frame-Options', 'SAMEORIGIN')
            ->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
    }

    public function saveEditorPages(Request $request)
    {
        /*$additionalPages=$this->additionalPageRepository()->getByHtmlFile();
        if($additionalPages){
            foreach($additionalPages as $page){
                $this->additionalPageRepository()->savePageHtmlData($page);
            }
        }

        $communityPages=$this->communityPagesRepository()->getByHtmlFile();
        if($communityPages){
            foreach($communityPages as $page){
                $this->communityPagesRepository()->savePageHtmlData($page);
            }
        }

        $communityHomePages=$this->communityHomeContentsRepository()->getByHtmlFile();
        if($communityHomePages){
            foreach($communityHomePages as $page){
                $this->communityHomeContentsRepository()->savePageHtmlData($page);
            }
        }

        $communityTemplates=$this->communityCampaignTemplatesRepository()->getByHtmlFile();
        if($communityTemplates){
            foreach($communityTemplates as $page){
                $this->communityCampaignTemplatesRepository()->savePageHtmlData($page);
            }
        }

        $communityCampaigns=$this->communityCampaignRepository()->getByHtmlFile();
        if($communityCampaigns){
            foreach($communityCampaigns as $page){
                $this->communityCampaignRepository()->savePageHtmlData($page);
            }
        }*/

        return 'false';
    }

    public function transPg($slug, $pageId,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');

        $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);

        $languages = $this->communityLanguagesRepository()->getByCommunityIdAll($this->community->id);

        $translatedData = $this->communityLanguagesTranslationRepository()->translatedData($this->community->id, 'page-data-'.$page->id);

        return $this->render('community.pannel.cms.pages.translate-page', ['page' => $page, 'languages' => $languages, 'translatedData' => $translatedData], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function translatePage($slug,Request $request)
    {
        $pageId = $request->get('id');
        $var = $request->get('lang');
        $type = $request->get('type');

        if ($type == 'page') {
            $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);

            $data = $page->html_code;
            $translatedData = translatePageLanguage($var, 'en', $data);

            $phrase = $this->communityLanguagesTranslationRepository()->translatePage($this->community->id, $var, $translatedData, 'page-data-'.$page->id);

        } else {

            $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

            $data = $contents->html_code;
            $translatedData = translatePageLanguage($var, 'en', $data);

            $phrase = $this->communityLanguagesTranslationRepository()->translatePage($this->community->id, $var, $translatedData, 'homepage-data-'.$this->community->id);
        }
    }

    public function editPagePhrase($slug, $pageId, $phrase_id,Request $request)
    {
        $phrase = $this->communityLanguagesTranslationRepository()->getByIdCommunity($this->community->id, $phrase_id);

        $page = $this->communityPagesRepository()->getByIdComId($pageId, $this->community->id);

        $language = app('App\\Repositories\\LanguageRepository')->findByVar($phrase->var);
        $message = null;
        if ($phrasevalue = $request->get('phrase-value')) {
            $this->communityLanguagesTranslationRepository()->translatePagePhrase($phrase, $phrasevalue);

            $message = trans('organizationlanguages.data-saved-successfully');
        }

        return $this->render('community.pannel.cms.pages.translate-page-phrase', ['phrase' => $phrase, 'page' => $page, 'language' => $language, 'message' => $message], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function homePageTranslation(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'pages');

        $community = $this->community;

        $languages = $this->communityLanguagesRepository()->getByCommunityIdAll($community->id);

        $translatedData = $this->communityLanguagesTranslationRepository()->translatedData($this->community->id, 'homepage-data-'.$community->id);

        return $this->render('community.pannel.cms.translate-homepage', ['languages' => $languages, 'translatedData' => $translatedData], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function editThemePhrase($slug, $phrase_id,Request $request)
    {
        $message = null;
        $phrase = $this->communityLanguagesTranslationRepository()->getByIdCommunity($this->community->id, $phrase_id);

        $language = app('App\\Repositories\\LanguageRepository')->findByVar($phrase->var);
        if ($phrasevalue = $request->get('phrase-value')) {
            $this->communityLanguagesTranslationRepository()->translatePagePhrase($phrase, $phrasevalue);
            $message = trans('organizationlanguages.data-saved-successfully');
        }

        return $this->render('community.pannel.cms.translate-homepage-phrase', ['phrase' => $phrase, 'language' => $language, 'message' => $message], [
            'title' => $this->setTitle(trans('page.pages')),
        ]);
    }

    public function pushCrmLeads(Request $request)
    {
        $campaignId = $request->get('id');

        if ($this->community->present()->canDoCampaign() == 0) {
            return redirect($this->community->present()->url());
        }

        $community = $this->community;

        $this->theme->share('settingPage', 'campaigns');
        $campaign = $this->communityCampaignRepository()->getByIdComId($campaignId, $this->community->id);
        $type = $request->get('type');

        $records = $this->communityCampaignEmailsSentRepository()->getByCommunityCampaignIdCat($this->community->id, $campaignId, $type);

        $crmUser = $this->userRepository()->getCrmUser(\Auth::user()->id, $community->id);
        if ($crmUser) {
            $lead_creatorid = $crmUser[0]->id;
            foreach ($records as $record) {

                $email_address = $record->email;

                $unsubscribed = $this->communityEmailsUnsubscribeRepository()->hasUnsubscribed($campaignId, $email_address);
                if (! $unsubscribed) {

                    $emailRecord = $this->communityCampaignEmailsRepository()->getById($record->campaign_email_id);

                    if ($emailRecord) {

                        $emailUserData = $this->communityMembersEmailsRepository()->getByCategoryId($email_address, $emailRecord->categories_id);

                        if ($emailUserData) {
                            $allRec = $this->communityCampaignEmailsSentRepository()->getByEmailId($campaign->id, $email_address);

                            $timesViewed = 0;
                            foreach ($allRec as $alrc) {
                                $timesViewed = $timesViewed + $alrc->seen;
                            }

                            $lead_title = $campaign->title;
                            $lead_firstname = $emailUserData->name;
                            $lead_lastname = $emailUserData->last_name;
                            $lead_phone = $emailUserData->contact;
                            $lead_job_position = $emailUserData->designation;
                            $lead_company_name = $emailUserData->company;
                            $lead_website = $emailUserData->website_url;
                            $lead_street = $emailUserData->address;

                            $lead_city = $record->city;
                            $lead_state = $record->state;
                            $lead_zip = '';
                            $lead_country = $record->country;
                            $lead_status = 1;

                            $view_times = $timesViewed;

                            $type = 'campaign';
                            $type_id = $campaignId;
                            $community_id = $community->id;

                            $lead_created = date('Y-m-d H:i:s');
                            $lead_updated = date('Y-m-d H:i:s');

                            if (! $this->crmLeadExist($email_address, $campaignId)) {
                                \DB::insert("insert into id_crm_leads(lead_title,lead_email,lead_firstname,lead_lastname,lead_phone,lead_job_position,lead_company_name,lead_website,lead_street,lead_city,lead_state,lead_zip,lead_country,lead_status,view_times,type,type_id,lead_creatorid,community_id,lead_created,lead_updated)values('".$lead_title."','".$email_address."','".$lead_firstname."','".$lead_lastname."','".$lead_phone."','".$lead_job_position."','".$lead_company_name."','".$lead_website."','".$lead_street."','".$lead_city."','".$lead_state."','".$lead_zip."','".$lead_country."',".$lead_status.','.$view_times.",'".$type."',".$type_id.','.$lead_creatorid.','.$community_id.",'".$lead_created."','".$lead_updated."')");
                            } else {
                                \DB::table('crm_leads')->where('lead_email', '=', $email_address)->where('type', '=', 'campaign')->where('type_id', '=', $campaignId)->update(['lead_firstname' => $lead_firstname, 'lead_lastname' => $lead_lastname, 'lead_phone' => $lead_phone, 'lead_job_position' => $lead_job_position, 'lead_company_name' => $lead_company_name, 'lead_website' => $lead_website, 'lead_street' => $lead_street, 'lead_city' => $lead_city, 'lead_state' => $lead_state, 'lead_zip' => $lead_zip, 'lead_country' => $lead_country, 'view_times' => $view_times, 'lead_updated' => $lead_updated]);
                            }

                            $note = $record->note;

                            $crmRecord = $this->crmLeadExist($email_address, $campaignId);

                            $leadId = $crmRecord[0]->lead_id;

                            $leadNote = $this->crmLeadNote('lead', $leadId);

                            if (! $leadNote) {
                                \DB::insert("insert into id_crm_notes(note_creatorid,note_description,noteresource_type,noteresource_id,community_id,note_created,note_updated)values('".$lead_creatorid."','".$note."','lead',".$leadId.','.$community_id.",'".$lead_created."','".$lead_updated."')");
                            } else {
                                \DB::table('crm_notes')->where('noteresource_type', '=', 'lead')->where('noteresource_id', '=', $leadId)->update(['note_description' => $note, 'note_updated' => $lead_updated]);
                            }
                        }
                    }
                }
            }
        }
    }

    public function crmLeadExist($email_address, $campaign_id)
    {
        $lead = \DB::select("SELECT * FROM id_crm_leads WHERE lead_email='".$email_address."' and type='campaign' and type_id='".$campaign_id."' ");

        return $lead;
    }

    public function crmLeadNote($type, $type_id)
    {
        $lead = \DB::select("SELECT * FROM id_crm_notes WHERE noteresource_type='".$type."' and noteresource_id='".$type_id."' ");

        return $lead;
    }

    public function seoContents(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $this->theme->share('settingPage', 'seocontents');

        $community = $this->community;
        $message = null;
        if ($val = $request->get('val')) {
            $community = $this->communityRepository()->updateSeoContents($val, $community);
            $message = 'SEO contents saved successfully.';
        }

        return $this->render('community.pannel.seo-contents', ['community' => $community, 'message' => $message], [
            'title' => $this->setTitle('SEO Contents'),
        ]);
    }

    public function makePlanPayment(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $type = $request->get('type');
        $plan_id = $request->get('plan_id');

        $community = $this->community;

        /*if ($plan_id == 4) {
            if ($community->special_plan_access == 0) {
                return redirect($community->present()->url('communitypayment'));
            }
        }*/

        $planDetails = $community->present()->getPlanDetails();
		
        /*if ($planDetails and $planDetails->paid_for_plan == 1) {
            $current_plan_id = $planDetails->plan_id;

			$updateMyPlan = 'yes';
			
            if ($updateMyPlan == 'yes') {
                $planStartDate = $planDetails->plan_end_date;
                if ($type == 'yearly') {
                    $planEndDate = date('Y-m-d', strtotime('+365 days', strtotime($planDetails->plan_end_date)));
                } else {
                    //$planStartDate = getRecurringMonthDate($planDetails->plan_end_date);
					$planEndDate = getRecurringMonthDate($planDetails->plan_end_date);
                }

                $planDetails->upcoming_plan_id = $plan_id;
                $planDetails->upcoming_plan_start_date = $planStartDate;
                $planDetails->upcoming_plan_end_date = $planEndDate;
                $planDetails->upcoming_plan_type = $type;
                $planDetails->upcoming_payment_id = '';
                $planDetails->save();

                \Session::flash('message', 'Your upcoming plan changed successfully');

                return redirect($community->present()->url('communitypayment'));
            }
        }*/

        $cmPlanDetails = $community->present()->getPricingPlan($plan_id);
        if ($cmPlanDetails and $cmPlanDetails->is_plan_free == 1) {
            $this->communityPricingPlanRepository()->saveFreePlan($community,$community->id, $community->user_id, $plan_id, $type);

            \Session::flash('community_plan_pay_message', 'Your plan changed successfully.');
            \Session::flash('community_plan_pay_message_type', 'success');
            \Session::flash('message', 'Your plan changed successfully.');

            return redirect($community->present()->url('communitypaymentplans'));
        }

        $coupon_applied = (int) $request->get('coupon_applied', 0);
        $coupon_code_applied = trim((string) $request->get('coupon_code_applied', ''));
        $coupon_discounted_price = (float) $request->get('coupon_discounted_price', 0);

        if ($coupon_applied === 1 && $coupon_discounted_price <= 0 && $cmPlanDetails) {
            $zeroPayMessage = '';
            $zeroPayTransactionId = '';
            try {
                $zeroPayTransactionId = $this->communityPricingPlanRepository()->payingForPlanByCard($community, $cmPlanDetails, $type, $coupon_applied, $coupon_code_applied, $coupon_discounted_price);
            } catch (\Throwable $e) {
                $zeroPayMessage = $e->getMessage();
            }

            if ($zeroPayTransactionId != '') {
                \Session::flash('community_plan_pay_message', 'Your payment successfully done.');
                \Session::flash('community_plan_pay_message_type', 'success');
                \Session::flash('community_plan_pay_transaction_id', $zeroPayTransactionId);
                \Session::flash('message', 'Your payment successfully done. Your transaction id is: '.$zeroPayTransactionId);

                return redirect($community->present()->url('communitypaymentplans'));
            }

            if (! $zeroPayMessage) {
                $zeroPayMessage = 'Payment failed.';
            }
            \Session::flash('community_plan_pay_message', $zeroPayMessage);
            \Session::flash('community_plan_pay_message_type', 'danger');
            \Session::flash('message', $zeroPayMessage);

            return redirect($community->present()->url('communitypaymentplans'));
        }

        $card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');
        if ($card) {
            $planDetails = $community->present()->getPricingPlan($plan_id);
            if ($planDetails) {
                $cardMessage = '';
                $hasPaymentDone = '';
                try {
                    $hasPaymentDone = $this->communityPricingPlanRepository()->payingForPlanByCard($community, $planDetails, $type, $coupon_applied, $coupon_code_applied, $coupon_discounted_price);
                } catch (\Throwable $e) {
                    $cardMessage = $e->getMessage();
                }

                if ($hasPaymentDone != '') {
                    \Session::flash('community_plan_pay_message', 'Your payment successfully done.');
                    \Session::flash('community_plan_pay_message_type', 'success');
                    \Session::flash('community_plan_pay_transaction_id', $hasPaymentDone);
                    \Session::flash('message', 'Your payment successfully done. Your transaction id is: '.$hasPaymentDone);

                    return redirect($community->present()->url('communitypaymentplans'));
                }

                if (! $cardMessage) {
                    $cardMessage = 'Payment failed.';
                }
                \Session::flash('community_plan_pay_message', $cardMessage);
                \Session::flash('community_plan_pay_message_type', 'danger');
                \Session::flash('message', $cardMessage);

                return redirect($community->present()->url('communitypaymentplans'));
            }
        }

        $pay_amount = '';

        if ($cmPlanDetails) {

            $purchased_space = $community->purchased_space_in_mb;
            $space_charges = config('community-space-monthly-charges-per-mb');
            $purchased_space_charges = '';

            $planDetails = $community->present()->getPricingPlan($plan_id);

            if ($type == 'yearly') {
                $pay_amount = $cmPlanDetails->price_yearly;

                $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan_id, $planDetails);
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                // $column_name="increased_member_limit_plan_".$plan_id;
                $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_plan_".$plan_id;
                $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;
                }
            }
        }

        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 payingForPlanUsers(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $message = 'Something went wrong, try again later.';

        if (! empty($request->get('stripeToken')) || $request->get('default_card') == 1 || (int) $request->get('pay_with_saved_card') === 1 || (int) $request->get('saved_card_id') > 0) {
            $number_of_users_in_plan = (int) $request->get('number_of_users_in_plan');
            $paying_for_months = (float) $request->get('paying_for_months');
            $amount_for_month = (float) $request->get('amount_for_month');
            $paying_ttl_amnt = (float) $request->get('paying_ttl_amnt');
            $stripeToken = $request->get('stripeToken');
            $currency_code = $request->get('currency_code');

            if ($number_of_users_in_plan <= 0 || $paying_for_months <= 0 || $amount_for_month < 0) {
                \Session::flash('pay_error_msg', 'Invalid subadmin quantity or amount.');

                return redirect($this->community->present()->url('communityplansubadminlimit'));
            }

            $base_paying_ttl_amnt = round(max(0, ($paying_for_months * $amount_for_month * $number_of_users_in_plan)), 2);
            $paying_ttl_amnt = $base_paying_ttl_amnt;
            $saved_card_id = (int) $request->get('saved_card_id');
            $paying_with_saved_card = (int) $request->get('pay_with_saved_card') === 1;
            if (! $paying_with_saved_card && $saved_card_id > 0) {
                $paying_with_saved_card = true;
            }

            $coupon_applied = (int) $request->get('coupon_applied', 0);
            $coupon_code_applied = trim((string) $request->get('coupon_code_applied', ''));
            $coupon_discounted_price = (float) preg_replace('/[^0-9.\-]/', '', (string) $request->get('coupon_discounted_price', '0'));

            $coupon_requested = ($coupon_applied === 1 && $coupon_code_applied !== '');
            $isCouponValid = false;

            if (! $coupon_requested) {
                $coupon_applied = 0;
                $coupon_code_applied = '';
                $coupon_discounted_price = 0;
            } else {
                $coupon = $this->communityCouponsRepository()->getByCodeActive($coupon_code_applied);
                if ($coupon) {
                    $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 ((int) $coupon->community_id === 0 || (int) $coupon->community_id === (int) $community->id) {
                            $baseAmount = (float) $base_paying_ttl_amnt;

                            if ($baseAmount < 0) {
                                $baseAmount = 0;
                            }

                            $discounted_amount = 0;
                            if ((int) $coupon->coupon_type === 1) {
                                $discount_percentage = (float) $coupon->discount_percentage;
                                if ($discount_percentage > 100) {
                                    $discount_percentage = 100;
                                }
                                if ($discount_percentage < 0) {
                                    $discount_percentage = 0;
                                }
                                $discounted_amount = ($baseAmount / 100) * $discount_percentage;
                            } else {
                                $discounted_amount = (float) $coupon->amount;
                            }

                            if ($discounted_amount > $baseAmount) {
                                $discounted_amount = $baseAmount;
                            }

                            $coupon_discounted_price = round(($baseAmount - $discounted_amount), 2);
                            if ($coupon_discounted_price < 0) {
                                $coupon_discounted_price = 0;
                            }

                            $isCouponValid = true;
                        }
                    }
                }

                if (! $isCouponValid) {
                    $coupon_applied = 0;
                    $coupon_code_applied = '';
                    $coupon_discounted_price = 0;

                    \Session::flash('pay_error_msg', 'Invalid or expired coupon code.');

                    return redirect($this->community->present()->url('communityplansubadminlimit'));
                }
            }

            if ($coupon_applied === 1) {
                $paying_ttl_amnt = $coupon_discounted_price;
            }

            $payingAmount = (int) round(((float) $paying_ttl_amnt) * 100);

            $has_default_card = $request->get('default_card');
            $orderId = rand(111111, 999999);

            $selected_saved_card = null;
            if ($paying_with_saved_card) {
                if (! $saved_card_id) {
                    \Session::flash('pay_error_msg', 'Please select a saved card.');

                    return redirect($this->community->present()->url('communityplansubadminlimit'));
                }

                $selected_saved_card = $this->communityPricingPlanPaymentCardsRepository()->getById($saved_card_id);
                if (! $selected_saved_card || (int) $selected_saved_card->community_id !== (int) $community->id || (int) $selected_saved_card->user_id !== (int) $community->user_id) {
                    \Session::flash('pay_error_msg', 'Invalid saved card selected.');

                    return redirect($this->community->present()->url('communityplansubadminlimit'));
                }
            }

            $planDetails = $community->present()->getPricingPlan($community->pricing_plan);

            if ($payingAmount > 0) {

                // require_once app_path('library/stripe-php/init.php');
                $stripe = [
                    'secret_key' => config('stripe_secret_key'),
                    'publishable_key' => config('stripe_publishable_key'),
                ];

                \Stripe\Stripe::setApiKey($stripe['secret_key']);

                if ($has_default_card == 1 || $paying_with_saved_card) {
                    $default_card = $selected_saved_card ? $selected_saved_card : $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');
                    if ($default_card) {
                        $cardMessage = '';

                        try {
                            $payDetails = \Stripe\Charge::create([
                                'customer' => $default_card->customer_id,
                                'amount' => $payingAmount,
                                'currency' => $currency_code,
                                'description' => 'subscription plan user limit',
                                'metadata' => [
                                    'order_id' => $orderId,
                                ],
                            ]);
                        } catch (\Stripe\Error\Base $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\Card $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\Authentication $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\InvalidRequest $e) {
                            $cardMessage = $e->getMessage();
                        } catch (Exception $e) {
                            $cardMessage = $e->getMessage();
                        }

                        if ($cardMessage) {
                            \Session::flash('pay_error_msg', $cardMessage);

                            return redirect($this->community->present()->url('communityplanuserlimit'));
                        }

                        $customerName = $community->user->fullname;
                        $customerEmail = $community->user->email_address;
                        $cardNumber = $default_card->card_number;
                        $cardCVC = '';
                        $cardExpMonth = $default_card->expiry_month;
                        $cardExpYear = $default_card->expiry_year;
                        $customer_id = $default_card->customer_id;
                        $itemName = $planDetails->plan_name;
                        $itemNumber = $planDetails->plan_id;
                        $payment_for = 'plan_limit';
                        $transaction_payment_type = 'community_user_plan_limit';
                        $plan_id = $planDetails->plan_id;

                        // $column_name="increased_member_limit_plan_".$plan_id;
                        $column_name = 'increased_member_limit';

                        $paymenyResponse = $payDetails->jsonSerialize();
                        if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                            $amountPaid = $paymenyResponse['amount'];
                            $amountPaid = $amountPaid / 100;
                            $balanceTransaction = $paymenyResponse['balance_transaction'];
                            $paidCurrency = $paymenyResponse['currency'];
                            $paymentStatus = $paymenyResponse['status'];
                            $paymentDate = date('Y-m-d H:i:s');
                            $itemPrice = $amountPaid;
                            $amountPaidNew = $amountPaid;

                            $message = 'Payment successfully done for '.$number_of_users_in_plan.' users, your transaction id - '.$balanceTransaction;

                            $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit($community, $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_id);

                            $increased_member_limit = $community->$column_name;
                            $community->$column_name = $number_of_users_in_plan + $increased_member_limit;
                            $community->save();

                            if ($payment) {
                                $val = [
                                    'currency' => $paidCurrency,
                                    'invoice_total_amount_price' => $amountPaidNew,
                                    'item_quantity' => $number_of_users_in_plan,
                                    'item_name' => 'purchase_extra_users_cost',
                                    'item_description' => $paying_for_months,
                                    'item_subtotal' => $amountPaidNew,
                                    'transaction_id' => $balanceTransaction,
                                    'item_price' => $amount_for_month,
                                ];

                                $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);

                                if ($invoice) {
                                    $payment->invoice_id = $invoice->id;
                                    $payment->save();

                                    $invoice->payment_id = $payment->id;
                                    $invoice->save();
                                }
                            }

                            app('App\\Repositories\\UserRepository')->sendPaymentAlertEmail('Community increase corporate user limit', $amountPaidNew, $balanceTransaction, $community->user->fullname, $community->user->email_address, $community->user->present()->url());
                        }
                    }
                } elseif ($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');
                    $address_unit = $request->get('address_unit');
                    $cardNumber = $request->get('cardNumber');
                    $cardCVC = $request->get('cardCVC');
                    $cardExpMonth = $request->get('cardExpMonth');
                    $cardExpYear = $request->get('cardExpYear');

                    $itemName = $planDetails->plan_name;
                    $itemNumber = $planDetails->plan_id;
                    $payment_for = 'plan_limit';
                    $transaction_payment_type = 'community_user_plan_limit';
                    $plan_id = $planDetails->plan_id;

                    $source_token = $stripeToken;

                    // $column_name="increased_member_limit_plan_".$plan_id;
                    $column_name = 'increased_member_limit';

                    $customer = \Stripe\Customer::create([
                        'name' => $customerName,
                        'description' => 'subscription plan user limit',
                        'email' => $customerEmail,
                        'source' => $source_token, // This is for test
                        'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
                    ]);

                    $cardMessage = '';

                    try {
                        $payDetails = \Stripe\Charge::create([
                            'customer' => $customer->id,
                            'amount' => $payingAmount,
                            'currency' => $currency_code,
                            'description' => $itemName,
                            'metadata' => [
                                'order_id' => $orderId,
                            ],
                        ]);
                    } catch (\Stripe\Error\Base $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\Card $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\Authentication $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\InvalidRequest $e) {
                        $cardMessage = $e->getMessage();
                    } catch (Exception $e) {
                        $cardMessage = $e->getMessage();
                    }

                    if ($cardMessage) {
                        \Session::flash('pay_error_msg', $cardMessage);

                        return redirect($this->community->present()->url('communityplanuserlimit'));
                    }

                    $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'];
                        $amountPaid = $amountPaid / 100;
                        $balanceTransaction = $paymenyResponse['balance_transaction'];
                        $paidCurrency = $paymenyResponse['currency'];
                        $paymentStatus = $paymenyResponse['status'];
                        $paymentDate = date('Y-m-d H:i:s');
                        $itemPrice = $amountPaid;
                        $amountPaidNew = $amountPaid;

                        $message = 'Payment successfully done for '.$number_of_users_in_plan.' users, your transaction id - '.$balanceTransaction;

                        $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit($community, $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_id, 'community', 'yes');

                        $increased_member_limit = $community->$column_name;
                        $community->$column_name = $number_of_users_in_plan + $increased_member_limit;
                        $community->save();

                        if ($payment) {
                            $val = [
                                'currency' => $paidCurrency,
                                'invoice_total_amount_price' => $amountPaidNew,
                                'item_quantity' => $number_of_users_in_plan,
                                'item_name' => 'purchase_extra_users_cost',
                                'item_description' => $paying_for_months,
                                'item_subtotal' => $amountPaidNew,
                                'transaction_id' => $balanceTransaction,
                                'item_price' => $amount_for_month,
                            ];

                            $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);

                            if ($invoice) {
                                $payment->invoice_id = $invoice->id;
                                $payment->save();

                                $invoice->payment_id = $payment->id;
                                $invoice->save();
                            }
                        }

                        app('App\\Repositories\\UserRepository')->sendPaymentAlertEmail('Community increase corporate user limit', $amountPaidNew, $balanceTransaction, $community->user->fullname, $community->user->email_address, $community->user->present()->url());
                    } else {
                        $message = 'Payment failed.';
                    }
                }
            } elseif ($coupon_applied === 1 && $payingAmount <= 0) {
                $plan_id = $planDetails->plan_id;
                $column_name = 'purchased_sub_admins';
                $itemName = $planDetails->plan_name;
                $itemNumber = $planDetails->plan_id;
                $payment_for = 'subadmin_limit';
                $transaction_payment_type = 'community_subadmin_plan_limit';
                $paidCurrency = $currency_code ? $currency_code : 'USD';
                $paymentStatus = 'succeeded';
                $paymentDate = date('Y-m-d H:i:s');
                $balanceTransaction = 'coupon_zero_'.uniqid('', true);
                $amountPaidNew = 0;
                $itemPrice = 0;

                $recordCard = null;
                if ($selected_saved_card) {
                    $recordCard = $selected_saved_card;
                } else {
                    $recordCard = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');
                }

                $cardNumber = $recordCard ? ($recordCard->card_number ?? '') : '';
                $cardExpMonth = $recordCard ? ($recordCard->expiry_month ?? '') : '';
                $cardExpYear = $recordCard ? ($recordCard->expiry_year ?? '') : '';
                $customer_id = $recordCard ? ($recordCard->customer_id ?? '') : '';
                $customerName = $community->user->fullname;
                $customerEmail = $community->user->email_address;

                $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit(
                    $community,
                    $community->user_id,
                    $customerName,
                    $customerEmail,
                    $cardNumber,
                    '',
                    $cardExpMonth,
                    $cardExpYear,
                    $itemName,
                    $itemNumber,
                    $itemPrice,
                    $paidCurrency,
                    $amountPaidNew,
                    $balanceTransaction,
                    $paymentStatus,
                    $paymentDate,
                    $payment_for,
                    $transaction_payment_type,
                    $customer_id,
                    $community->id,
                    $plan_id
                );

                $increased_member_limit = $community->$column_name;
                $community->$column_name = $number_of_users_in_plan + $increased_member_limit;
                $community->save();

                $data = $this->communityPricingPlanRepository()->saveUsersPlan($community, $community->id, $community->user_id, $plan_id, 'monthly', 'subadmin');
                if ($payment && $data) {
                    $data->payment_id = $payment->id;
                    $data->save();

                    $this->communityCouponsRepository()->updateCouponStatus($coupon_code_applied, (int) (\Auth::id() ?? 0), 'community_subadmin_limit', (int) $payment->id);

                    $val = [
                        'currency' => $paidCurrency,
                        'invoice_total_amount_price' => 0,
                        'item_quantity' => $number_of_users_in_plan,
                        'item_name' => 'purchase_extra_subadmin_cost',
                        'item_description' => $paying_for_months,
                        'item_subtotal' => 0,
                        'transaction_id' => $balanceTransaction,
                        'item_price' => $amount_for_month,
                    ];

                    $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);
                    if ($invoice) {
                        $payment->invoice_id = $invoice->id;
                        $payment->save();

                        $invoice->payment_id = $payment->id;
                        $invoice->save();
                    }
                }

                $message = 'Payment successfully done for '.$number_of_users_in_plan.' subadmins, your transaction id - '.$balanceTransaction;
            }
        }

        \Session::flash('message', $message);

        return redirect($this->community->present()->url('communityplanuserlimit'));
    }
	
	
	public function payingForPlanSubAdmins(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $message = 'Something went wrong, try again later.';

        $number_of_users_in_plan = (int) $request->get('number_of_users_in_plan');
        $paying_for_months = (float) $request->get('paying_for_months', 1);
        $amount_for_month = (float) $request->get('amount_for_month', 0);
        $stripeToken = (string) $request->get('stripeToken', '');
        $currency_code = (string) $request->get('currency_code', 'USD');
        $saved_card_id = (int) $request->get('saved_card_id');
        $paying_with_saved_card = (int) $request->get('pay_with_saved_card') === 1;
        $has_default_card = (int) $request->get('default_card') === 1;

        if (! $paying_with_saved_card && $saved_card_id > 0) {
            $paying_with_saved_card = true;
        }

        if ($number_of_users_in_plan <= 0 || $paying_for_months <= 0 || $amount_for_month < 0) {
            \Session::flash('pay_error_msg', 'Invalid subadmin quantity or amount.');

            return redirect($this->community->present()->url('members'));
        }

        $base_paying_ttl_amnt = round(max(0, ($paying_for_months * $amount_for_month * $number_of_users_in_plan)), 2);
        $paying_ttl_amnt = $base_paying_ttl_amnt;

        $coupon_applied = (int) $request->get('coupon_applied', 0);
        $coupon_code_applied = trim((string) $request->get('coupon_code_applied', ''));
        $coupon_discounted_price = (float) preg_replace('/[^0-9.\-]/', '', (string) $request->get('coupon_discounted_price', '0'));
        $coupon_discount_percentage_value = 0;
        $coupon_requested = ($coupon_applied === 1 && $coupon_code_applied !== '');

        if (! $coupon_requested) {
            $coupon_applied = 0;
            $coupon_code_applied = '';
            $coupon_discounted_price = 0;
        } else {
            $coupon = $this->communityCouponsRepository()->getByCodeActive($coupon_code_applied);
            $isCouponValid = false;
            if ($coupon) {
                $from_date = $coupon->valid_from;
                $valid_to = $coupon->valid_to;
                $todays_date = date('Y-m-d');
                if ($todays_date >= $from_date && $todays_date <= $valid_to) {
                    if ((int) $coupon->community_id === 0 || (int) $coupon->community_id === (int) $community->id) {
                        $discounted_amount = 0;
                        if ((int) $coupon->coupon_type === 1) {
                            $discount_percentage = (float) $coupon->discount_percentage;
                            if ($discount_percentage > 100) {
                                $discount_percentage = 100;
                            }
                            if ($discount_percentage < 0) {
                                $discount_percentage = 0;
                            }
                            $coupon_discount_percentage_value = $discount_percentage;
                            $discounted_amount = ($base_paying_ttl_amnt / 100) * $discount_percentage;
                        } else {
						    $discount_percentage = (float) $coupon->amount;
                            $discounted_amount = (float) $coupon->amount;
                            $coupon_discount_percentage_value = 0;
                        }

                        if ($discounted_amount > $base_paying_ttl_amnt) {
                            $discounted_amount = $base_paying_ttl_amnt;
                        }

                        $coupon_discounted_price = round(($base_paying_ttl_amnt - $discounted_amount), 2);
                        if ($coupon_discounted_price < 0) {
                            $coupon_discounted_price = 0;
                        }

                        $isCouponValid = true;
                    }
                }
            }

            if (! $isCouponValid) {
                \Session::flash('pay_error_msg', 'Invalid or expired coupon code.');

                return redirect($this->community->present()->url('members'));
            }
        }

        if ($coupon_applied === 1) {
            $paying_ttl_amnt = $coupon_discounted_price;
        }

        $payingAmount = (int) round(((float) $paying_ttl_amnt) * 100);
        if ($payingAmount <= 0 && $coupon_applied !== 1) {
            \Session::flash('pay_error_msg', 'Amount should be greater than 0.');

            return redirect($this->community->present()->url('members'));
        }

        if ($payingAmount > 0 && ! $stripeToken && ! $has_default_card && ! $paying_with_saved_card) {
            \Session::flash('pay_error_msg', 'Select a payment method to proceed.');

            return redirect($this->community->present()->url('members'));
        }

        $selected_saved_card = null;
        if ($paying_with_saved_card) {
            if (! $saved_card_id) {
                \Session::flash('pay_error_msg', 'Please select a saved card.');

                return redirect($this->community->present()->url('members'));
            }

            $selected_saved_card = $this->communityPricingPlanPaymentCardsRepository()->getById($saved_card_id);
            if (! $selected_saved_card || (int) $selected_saved_card->community_id !== (int) $community->id || (int) $selected_saved_card->user_id !== (int) $community->user_id) {
                \Session::flash('pay_error_msg', 'Invalid saved card selected.');

                return redirect($this->community->present()->url('members'));
            }
        }

        $planDetails = $community->present()->getPricingPlan($community->pricing_plan);
        if (! $planDetails) {
            \Session::flash('pay_error_msg', 'Plan details not found.');

            return redirect($this->community->present()->url('members'));
        }

        $plan_id = $planDetails->plan_id;
        $column_name = 'purchased_sub_admins';
        $itemName = $planDetails->plan_name;
        $itemNumber = $planDetails->plan_id;
        $orderId = rand(111111, 999999);

        $finalizeSubadminPayment = function ($payment, $amountPaidNew, $paidCurrency, $balanceTransaction) use ($community, $number_of_users_in_plan, $column_name, $plan_id, $coupon_applied, $coupon_code_applied, $coupon_discount_percentage_value, $base_paying_ttl_amnt, $paying_for_months, $amount_for_month) {
            $increased_member_limit = $community->$column_name;
            $community->$column_name = $number_of_users_in_plan + $increased_member_limit;
            $community->save();

            $data = $this->communityPricingPlanRepository()->saveUsersPlan($community, $community->id, $community->user_id, $plan_id, 'monthly', 'subadmin');
            if ($payment && $data) {
                try {
                    $payment->coupon_applied = ($coupon_applied === 1) ? 1 : 0;
                    $payment->coupon_code = ($coupon_applied === 1) ? $coupon_code_applied : '';
                    $payment->discount_percentage = ($coupon_applied === 1) ? $coupon_discount_percentage_value : 0;
                    $payment->actual_amount = $base_paying_ttl_amnt;
                    $payment->save();
                } catch (\Throwable $e) {
                    // Keep payment flow successful even if optional coupon columns are unavailable.
                }

                $data->payment_id = $payment->id;
				$data->added_users = $number_of_users_in_plan;
				$data->price_per_user = $amount_for_month;
                $data->save();

                if ($coupon_applied === 1 && $coupon_code_applied !== '') {
                    $this->communityCouponsRepository()->updateCouponStatus($coupon_code_applied, (int) (\Auth::id() ?? 0), 'community_subadmin_limit', (int) $payment->id);
                }

                $val = [
                    'currency' => $paidCurrency,
                    'invoice_total_amount_price' => $amountPaidNew,
                    'item_quantity' => $number_of_users_in_plan,
                    'item_name' => 'purchase_extra_subadmin_cost',
                    'item_description' => $paying_for_months,
                    'item_subtotal' => $amountPaidNew,
                    'transaction_id' => $balanceTransaction,
                    'item_price' => $amount_for_month,
                ];

                $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);
                if ($invoice) {
                    $payment->invoice_id = $invoice->id;
                    $payment->save();

                    $invoice->payment_id = $payment->id;
                    $invoice->save();
                }
            }
        };

        if ($payingAmount > 0) {
            $stripe = [
                'secret_key' => config('stripe_secret_key'),
                'publishable_key' => config('stripe_publishable_key'),
            ];
            \Stripe\Stripe::setApiKey($stripe['secret_key']);

            if ($has_default_card || $paying_with_saved_card) {
                $default_card = $selected_saved_card ? $selected_saved_card : $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');
                if (! $default_card) {
                    \Session::flash('pay_error_msg', 'No saved/default card found.');

                    return redirect($this->community->present()->url('members'));
                }

                $cardMessage = '';
                try {
                    $payDetails = \Stripe\Charge::create([
                        'customer' => $default_card->customer_id,
                        'amount' => $payingAmount,
                        'currency' => $currency_code,
                        'description' => 'Add subadmin',
                        'metadata' => ['order_id' => $orderId],
                    ]);
                } catch (\Stripe\Error\Base $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\Card $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\Authentication $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\InvalidRequest $e) {
                    $cardMessage = $e->getMessage();
                } catch (Exception $e) {
                    $cardMessage = $e->getMessage();
                }

                if ($cardMessage) {
                    \Session::flash('pay_error_msg', $cardMessage);

                    return redirect($this->community->present()->url('members'));
                }

                $paymenyResponse = $payDetails->jsonSerialize();
                if (!($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1)) {
                    \Session::flash('pay_error_msg', 'Payment failed.');

                    return redirect($this->community->present()->url('members'));
                }

                $amountPaidNew = ((float) $paymenyResponse['amount']) / 100;
                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');

                $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit(
                    $community,
                    $community->user_id,
                    $community->user->fullname,
                    $community->user->email_address,
                    $default_card->card_number,
                    '',
                    $default_card->expiry_month,
                    $default_card->expiry_year,
                    $itemName,
                    $itemNumber,
                    $amountPaidNew,
                    $paidCurrency,
                    $amountPaidNew,
                    $balanceTransaction,
                    $paymentStatus,
                    $paymentDate,
                    'subadmin_limit',
                    'community_subadmin_plan_limit',
                    $default_card->customer_id,
                    $community->id,
                    $plan_id
                );

                $finalizeSubadminPayment($payment, $amountPaidNew, $paidCurrency, $balanceTransaction);
                $message = 'Payment successfully done for '.$number_of_users_in_plan.' subadmins, your transaction id - '.$balanceTransaction;
            } elseif ($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');

                $customer = \Stripe\Customer::create([
                    'name' => $customerName,
                    'description' => 'Add subadmin',
                    'email' => $customerEmail,
                    'source' => $stripeToken,
                    'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
                ]);

                $cardMessage = '';
                try {
                    $payDetails = \Stripe\Charge::create([
                        'customer' => $customer->id,
                        'amount' => $payingAmount,
                        'currency' => $currency_code,
                        'description' => $itemName,
                        'metadata' => ['order_id' => $orderId],
                    ]);
                } catch (\Stripe\Error\Base $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\Card $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\Authentication $e) {
                    $cardMessage = $e->getMessage();
                } catch (\Stripe\Error\InvalidRequest $e) {
                    $cardMessage = $e->getMessage();
                } catch (Exception $e) {
                    $cardMessage = $e->getMessage();
                }

                if ($cardMessage) {
                    \Session::flash('pay_error_msg', $cardMessage);

                    return redirect($this->community->present()->url('members'));
                }

                $paymenyResponse = $payDetails->jsonSerialize();
                if (!($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1)) {
                    \Session::flash('pay_error_msg', 'Payment failed.');

                    return redirect($this->community->present()->url('members'));
                }

                $amountPaidNew = ((float) $paymenyResponse['amount']) / 100;
                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');

                $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit(
                    $community,
                    $community->user_id,
                    $customerName,
                    $customerEmail,
                    $cardNumber,
                    $cardCVC,
                    $cardExpMonth,
                    $cardExpYear,
                    $itemName,
                    $itemNumber,
                    $amountPaidNew,
                    $paidCurrency,
                    $amountPaidNew,
                    $balanceTransaction,
                    $paymentStatus,
                    $paymentDate,
                    'plan_subadmin_limit',
                    'community_subadmin_plan_limit',
                    $customer->id,
                    $community->id,
                    $plan_id,
                    'community',
                    'yes'
                );

                $finalizeSubadminPayment($payment, $amountPaidNew, $paidCurrency, $balanceTransaction);
                $message = 'Payment successfully done for '.$number_of_users_in_plan.' subadmins, your transaction id - '.$balanceTransaction;
            }
        } elseif ($coupon_applied === 1 && $payingAmount <= 0) {
            $recordCard = $selected_saved_card ? $selected_saved_card : $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

            $cardNumber = $recordCard ? ($recordCard->card_number ?? '') : '';
            $cardExpMonth = $recordCard ? ($recordCard->expiry_month ?? '') : '';
            $cardExpYear = $recordCard ? ($recordCard->expiry_year ?? '') : '';
            $customer_id = $recordCard ? ($recordCard->customer_id ?? '') : '';

            $balanceTransaction = 'coupon_zero_'.uniqid('', true);
            $paidCurrency = $currency_code ? $currency_code : 'USD';

            $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit(
                $community,
                $community->user_id,
                $community->user->fullname,
                $community->user->email_address,
                $cardNumber,
                '',
                $cardExpMonth,
                $cardExpYear,
                $itemName,
                $itemNumber,
                0,
                $paidCurrency,
                0,
                $balanceTransaction,
                'succeeded',
                date('Y-m-d H:i:s'),
                'subadmin_limit',
                'community_subadmin_plan_limit',
                $customer_id,
                $community->id,
                $plan_id
            );

            $finalizeSubadminPayment($payment, 0, $paidCurrency, $balanceTransaction);
            $message = 'Payment successfully done for '.$number_of_users_in_plan.' subadmins, your transaction id - '.$balanceTransaction;
        }

        \Session::flash('message', $message);

        return redirect($this->community->present()->url('members'));
    }
	
	

    /*public function payingForPlan()
    {
        if (!($this->community->isOwner())) redirect('home')->send();

        $community=$this->community;

        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 = array(
                      "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(array(
                    'name' => $customerName,
                    'description' => 'Community Plan',
                    'email' => $customerEmail,
                    'source'  => $source_token, //This is for test
                    "address" => ["city" => $customerCity, "country" => $customerCountry, "line1" => $customerAddress, "line2" => "", "postal_code" => $customerZipcode, "state" => $customerState]
                ));

                $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');

                $payDetails = \Stripe\Charge::create(array(
                    'customer' => $customer->id,
                    'amount'   => $totalAmount,
                    'currency' => $currency,
                    'description' => $itemName,
                    'metadata' => array(
                        '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;

                    $user_id = \Auth::user()->id;

                    $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);

                    $purchasemessage = "You have successfully purchased the plan. Your transaction id is - ".$balanceTransaction;
                } else{
                    $purchasemessage = "Payment failed.";
                }

                return $this->render('community.pannel.plan.make-payment',['type'=>$payment_type,'plan_id'=>"",'purchasemessage'=>$purchasemessage], [
                    'title' => $this->setTitle("Pages")
                ]);
          }
    }*/

    public function communityPayment()
    {
        if (! \Auth::check()) {
            $community_subscription_url = $this->community->present()->url('communitypayment');

            return redirect($this->community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community_subscription_url]));
        }

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->community;
		
		$community_subscription_url = $this->community->present()->url('communitypaymentplans');
		
		 return redirect($community_subscription_url);

        $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('community.pannel.plan.plan-details', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card,'allPlans'=>$allPlans,'planFeaturesByPlanId'=>$planFeaturesByPlanId], [
            'title' => $this->setTitle('Community Payment'),
        ]);
    }
	
	public function communityPaymentPlans()
    {
        if (! \Auth::check()) {
            $community_subscription_url = $this->community->present()->url('communitypayment');

            return redirect($this->community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community_subscription_url]));
        }

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->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();
		
		if($planDetails){
			$allPlans=$this->pricingPlansRepository()->getRelatedPlans($planDetails->plan_id);
		}else{
			$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('community.pannel.plan.plans', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card,'allPlans'=>$allPlans,'planFeaturesByPlanId'=>$planFeaturesByPlanId], [
            'title' => $this->setTitle(trans('internal-collaborations.community-payment')),
        ]);
    }
	
	public function communityServerSpace()
    {
        if (! \Auth::check()) {
            $community_subscription_url = $this->community->present()->url('communitypayment');

            return redirect($this->community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community_subscription_url]));
        }

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->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');

        return $this->render('community.pannel.plan.server-space', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card], [
            'title' => $this->setTitle('Community Payment'),
        ]);
    }
	
	public function communityPaymentMethods(\Illuminate\Http\Request $request)
    {
        if (! \Auth::check()) {
            $community_subscription_url = $this->community->present()->url('communitypayment');

            return redirect($this->community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community_subscription_url]));
        }

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->community;

        // Update auto-renewal (stop_payment) via AJAX POST
        if ($request->isMethod('post')) {
            $stopPayment = (int) $request->get('stop_payment', -1);
            if (!in_array($stopPayment, [0, 1], true)) {
                if ($request->ajax() || $request->wantsJson()) {
                    return response()->json(['ok' => false, 'message' => 'Invalid value'], 422);
                }

                \Session::flash('message', 'Invalid value');
                return redirect($community->present()->url('communitypaymentmethods'));
            }

            $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);
            if (!$planDetails) {
                if ($request->ajax() || $request->wantsJson()) {
                    return response()->json(['ok' => false, 'message' => 'Plan not found'], 404);
                }

                \Session::flash('message', 'Plan not found');
                return redirect($community->present()->url('communitypaymentmethods'));
            }

            $planDetails->stop_payment = $stopPayment;
            $planDetails->save();

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json(['ok' => true, 'stop_payment' => $stopPayment]);
            }

            \Session::flash('message', 'Updated successfully');
            return redirect($community->present()->url('communitypaymentmethods'));
        }

        $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');       
        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

        return $this->render('community.pannel.plan.payment-methods', ['cards' => $cards, 'default_card' => $default_card], [
            'title' => $this->setTitle(trans('internal-collaborations.community-payment')),
        ]);
    }


    public function aiChatbotSetting(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        if ($val = $request->get('val')) {
            $addContents = $this->communityHomeContentsRepository()->aiChatbotSetting($val, $this->community->id);

            return redirect($this->community->present()->url('aichatbot'))->with('success', trans('cms.settings-saved-successfully'));
        }

        $contents = $this->communityHomeContentsRepository()->getByCommunityId($this->community->id);

        if ((! $contents) || ($contents and $contents->has_pushed_default_ai == 0)) {
            $contents = $this->communityHomeContentsRepository()->aiChatbotPushDefault($community->id);
        }

        return $this->render('community.pannel.cms.chatbot-settings', ['community' => $community, 'contents' => $contents], [
            'title' => $this->setTitle(trans('cms.chatbot-setting')),
        ]);
    }

    public function communityPlanUserLimit()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->community;

        $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');
        $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);

        $plan = $community->present()->getPricingPlan($planDetails->plan_id);

        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

        return $this->render('community.pannel.plan.increase-user-limit', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card, 'plan' => $plan], [
            'title' => $this->setTitle('Community Payment'),
        ]);
    }
	
	public function communityPlanSubAdminLimit()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
		
		redirect('home')->send();

        $community = $this->community;

        $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');
        $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);

        $plan = $community->present()->getPricingPlan($planDetails->plan_id);

        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

		if($community->present()->canAddExtraSubAdmins()){
			return $this->render('community.pannel.plan.increase-sub-admin-limit', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card, 'plan' => $plan], [
				'title' => $this->setTitle('Community Payment'),
			]);
		}
		
		 return redirect(\URL::previous());	
    }
	

    public function communityPaymentAddMethod()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

        return $this->render('community.pannel.plan.add-card', ['default_card' => $default_card], [
            'title' => $this->setTitle(trans('internal-collaborations.add-payment-method')),
        ]);
    }

    public function communityPaymentHistory(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $selected_year = $request->get('selected_year');
        if (! $selected_year) {
            $selected_year = date('Y');
        }

        // $addPaymentPending=$this->communityPricingPlanPaymentRepository()->updatePaymentStatus();

        $min_year = $this->communityPricingPlanPaymentRepository()->getMinRecordYear($community->id);

        return $this->render('community.pannel.plan.payment-history',
            [
                'selected_year' => $selected_year,
                'min_year' => $min_year,
            ],
            ['title' => $this->setTitle('Community Payment History')]
        );

        // $min_year=$this->communityPricingPlanPaymentRepository()->getMinRecordYear($community->id);
        // $first_record=$this->communityPricingPlanPaymentRepository()->getFirstSubscriptionRecord($community->id);
        // $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);

        /*return $this->render('community.pannel.plan.payment-history',
            [
                'selected_year'=>$selected_year,
                'min_year'=>$min_year,
                'first_record'=>$first_record,
                'planDetails'=>$planDetails
            ],
            ['title' => $this->setTitle("Community Payment History")]
        );*/
    }

    public function communityPaymentTransactions()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $transactions = $this->communityPricingPlanPaymentRepository()->getCmSubscriptionTransactions($community->id);
        $pendingInvoice = $this->communityInvoiceRepository()->pendingSubscriptionInvoice($community->id);
        $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);
        $plan = '';
        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);
        }

        return $this->render('community.pannel.plan.payment-transactions',
            [
                'transactions' => $transactions,
                'pendingInvoice' => $pendingInvoice,
                'planDetails' => $planDetails,
                'plan' => $plan,
            ],
            ['title' => $this->setTitle(trans('internal-collaborations.community-transactions'))]
        );
    }

    public function communityPaymentCardMakeDefault($slug, $id)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        \Session::flash('message', trans('internal-collaborations.something-went-wrong'));
        $card = $this->communityPricingPlanPaymentCardsRepository()->getById($id);
        if ($card and $card->community_id == $community->id) {

            $this->communityPricingPlanPaymentCardsRepository()->removeOtherDefault($community);

            $card->is_default = 1;
            $card->save();

            \Session::flash('message', trans('internal-collaborations.set-as-default-done-successfully'));
        }

        return redirect($this->community->present()->url('communitypaymentmethods'));
    }

    public function communityPaymentCardDelete($slug, $id)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        \Session::flash('message', trans('internal-collaborations.something-went-wrong'));
        $card = $this->communityPricingPlanPaymentCardsRepository()->getById($id);
        if ($card and $card->community_id == $community->id) {
            $card->delete();
            \Session::flash('message', trans('internal-collaborations.card-deleted-successfully'));
        }

        return redirect($this->community->present()->url('communitypaymentmethods'));
    }

    public function communityPaymentCardEdit($slug, $id)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $card = $this->communityPricingPlanPaymentCardsRepository()->getById($id);
        if ($card and $card->community_id == $community->id) {
            $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

            return $this->render('community.pannel.plan.edit-card', ['card' => $card, 'default_card' => $default_card], [
                'title' => $this->setTitle(trans('internal-collaborations.edit-card')),
            ]);
        }

        return redirect($this->community->present()->url('communitypayment'));
    }

    public function getdefaultcarddetails()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;
        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

        return json_encode([
            'card_name' => $default_card->card_name,
            'billing_address' => $default_card->billing_address,
            'city' => $default_card->city,
            'state' => $default_card->state,
            'country' => $default_card->country,
            'zip' => $default_card->zip,
        ]);
    }

    public function communityPaymentAddCard(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $my_uuid = \Auth::user()->id;
        $my_community_id = $this->community->id;

        $stripeToken = $request->get('stripeToken');
        $card_number = $request->get('card_number');
        $card_name = $request->get('card_name');
        $card_cvv = $request->get('card_cvv');
        $billing_address = $request->get('billing_address');
        $card_month = $request->get('card_month');
        $card_year = $request->get('card_year');
        $billing_city = $request->get('billing_city');
        $billing_state = $request->get('billing_state');
        $billing_country = $request->get('billing_country');
        $billing_zip = $request->get('billing_zip');
        $set_as_default = $request->get('set_as_default');
        if (! $set_as_default) {
            $set_as_default = 0;
        }

        // If a default card already exists, don't auto-promote a newly added card.
        // Users can still set a different default from the payment methods listing.
        $existingDefault = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($my_community_id, $my_uuid, 'community_plan', 'community');
        if ($existingDefault) {
            $set_as_default = 0;
        }

        $user = \Auth::user();

        if (! empty($request->get('stripeToken'))) {
            if ($user) {

                // 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']);

                $card_brand = '';
                $card_country = '';
                try {
                    $token = \Stripe\Token::retrieve($stripeToken);
                    if ($token && isset($token->card)) {
                        $card_brand = isset($token->card->brand) ? $token->card->brand : '';
                        $card_country = isset($token->card->country) ? $token->card->country : '';
                    }
                } catch (\Exception $e) {
                    // Best-effort only; card brand/country will remain empty.
                }

                $customer = \Stripe\Customer::create([
                    'name' => $card_name,
                    'description' => 'Plan Payment',
                    'email' => $user->email_address,
                    'source' => $source_token, // This is for test
                    'address' => ['city' => $billing_city, 'country' => $billing_country, 'line1' => $billing_address, 'line2' => '', 'postal_code' => $billing_zip, 'state' => $billing_state],
                ]);

                if ($community and $community->user_id == $my_uuid and $customer) {
                    $card = $this->communityPricingPlanPaymentCardsRepository()->addPaymentCard($my_community_id, $my_uuid, $card_number, $card_month, $card_year, $card_name, $billing_address, $card_cvv, $billing_city, $billing_state, $billing_country, $billing_zip, $customer->id, 'community_plan', $set_as_default, 'community', $stripeToken, $card_brand, $card_country);

                    $community->card_dtls_added = 1;
                    $community->save();

                    \Session::flash('message', 'Card details added successfully.');

                    return redirect($this->community->present()->url('communitypaymentaddmethod'));
                }
            }
        }

        \Session::flash('message', 'Something went wrong, try again later.');

        return redirect($this->community->present()->url('communitypaymentaddmethod'));
    }

    public function communityPaymentEditingCard($slug, $id,Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $my_uuid = \Auth::user()->id;
        $my_community_id = $this->community->id;

        $stripeToken = $request->get('stripeToken');
        $card_number = $request->get('card_number');
        $card_name = $request->get('card_name');
        $card_cvv = $request->get('card_cvv');
        $billing_address = $request->get('billing_address');
        $card_month = $request->get('card_month');
        $card_year = $request->get('card_year');
        $billing_city = $request->get('billing_city');
        $billing_state = $request->get('billing_state');
        $billing_country = $request->get('billing_country');
        $billing_zip = $request->get('billing_zip');
        $set_as_default = $request->get('set_as_default');
        if (! $set_as_default) {
            $set_as_default = 0;
        }

        // If a default card already exists and we're not editing it, don't auto-promote this card.
        $existingDefault = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($my_community_id, $my_uuid, 'community_plan', 'community');
        if ($existingDefault && (int) $existingDefault->id !== (int) $id) {
            $set_as_default = 0;
        }

        $user = \Auth::user();

        if (! empty($request->get('stripeToken'))) {
            $card = $this->communityPricingPlanPaymentCardsRepository()->getById($id);
            if ($card and $card->community_id == $community->id) {

                // 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']);

                $card_brand = '';
                $card_country = '';
                try {
                    $token = \Stripe\Token::retrieve($stripeToken);
                    if ($token && isset($token->card)) {
                        $card_brand = isset($token->card->brand) ? $token->card->brand : '';
                        $card_country = isset($token->card->country) ? $token->card->country : '';
                    }
                } catch (\Exception $e) {
                    // Best-effort only; card brand/country will remain empty.
                }

                $customer = \Stripe\Customer::create([
                    'name' => $card_name,
                    'description' => 'Plan Payment',
                    'email' => $user->email_address,
                    'source' => $source_token, // This is for test
                    'address' => ['city' => $billing_city, 'country' => $billing_country, 'line1' => $billing_address, 'line2' => '', 'postal_code' => $billing_zip, 'state' => $billing_state],
                ]);

                if ($customer) {
                    $this->communityPricingPlanPaymentCardsRepository()->editPaymentCard($card, $card_number, $card_month, $card_year, $card_name, $billing_address, $card_cvv, $billing_city, $billing_state, $billing_country, $billing_zip, $customer->id, 'community_plan', $set_as_default, 'community', $stripeToken, $card_brand, $card_country);

                    $community->card_dtls_added = 1;
                    $community->save();

                    \Session::flash('message', 'Card details edited successfully.');

                    return redirect($this->community->present()->url('communitypaymentcardedit').'/'.$id);
                }
            }
        }

        \Session::flash('message', 'Something went wrong, try again later.');

        return redirect($this->community->present()->url('communitypaymentcardedit').'/'.$id);
    }

    public function executePlanPayments()
    {
        return $this->communityPricingPlanRepository()->makePlanPayment();
    }

    public function giftsCreated()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;

        $allgifts = $this->giftsRepository()->allParentGifts($community->id);

        return $this->render('community.pannel.gifts.gifts-list', ['allgifts' => $allgifts], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function giftContributers($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;

        $gift = $this->giftsRepository()->getByCmId($community->id, $id);
        if ($gift) {
            $contributers = $this->giftsContributionRepository()->getByIdAll($id);

            return $this->render('community.pannel.gifts.gift-contributers', ['gift' => $gift, 'contributers' => $contributers]);

        } else {
            return redirect($this->community->present()->url('gifts/mygifts'));
        }
    }

    public function giftsDashboard()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $communityPayments = $this->giftsAccountCommunityRepository()->getByCommunityId($community->id);

        return $this->render('community.pannel.gifts.payment-overview', ['communityPayments' => $communityPayments]);
    }

    public function giftReimbursement(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $id = $request->get('id');
        $gift = $this->giftsRepository()->getByCmId($community->id, $id);
        if ($gift) {
            /*$gift->has_money_collected=1;
            $gift->save();

            if($gift->parent_gift_id){
                $parent_id=$gift->parent_gift_id;
                $nextPayingNumber=$gift->paying_number+1;

                $this->giftsRepository()->startCollectingNext($community->id,$parent_id,$nextPayingNumber,$gift->community_gift_id);

                //$this->giftsRepository()->startCollectingChild($community->id,$gift->id);
            }else{
                $nextPayingNumber=$gift->paying_number+1;
                $parent_id=$gift->id;
                $this->giftsRepository()->startCollectingNext($community->id,$parent_id,$nextPayingNumber);
            }

            $collected_amt=$gift->total_amt_collected;
            $original_amt = $collected_amt-$gift->amount;
            $amt_commission= ($original_amt/100)*10;
            $amt = $original_amt-$amt_commission;

            $full_date=date("Y-m-d H:i:s");
            $user_id = $gift->user_id;

            $this->giftsAccountCommunityRepository()->updateReimbursement($community->id,$amt);

            $this->giftsTransactionsRepository()->doTransaction($community->id,$community->user_id,$amt,$amt,$full_date,'reimbursement',$gift->id,$user_id);

            $this->giftsAccountRepository()->fundAccount($community->id,$user_id,$amt,$amt,$full_date,'reimbursement');*/

            $this->giftsRepository()->makeReimbursment($community, $gift);

        } else {
            return redirect($this->community->present()->url('gifts/mygifts'));
        }
    }

    public function manageGifts()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $gifts = $this->giftsCommunityRepository()->allGifts($community->id);

        return $this->render('community.pannel.gifts.manage-gifts', ['gifts' => $gifts]);
    }

    public function addGiftAmt(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        if ($val = $request->get('val')) {
            $gift_amount_send = $val['gift_amount_send'];
            $gift_amount_multiplied_by = $val['amount_multiplied_by'];

            $gift = $this->giftsCommunityRepository()->addGift($community->id, \Auth::user()->id, $gift_amount_send, $gift_amount_multiplied_by);

            \Session::flash('message', 'Gift added successfully.');

            return redirect($this->community->present()->url('managegifts'));
        }

        return $this->render('community.pannel.gifts.add-gift');
    }

    public function deleteGift($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $this->giftsCommunityRepository()->deleteGift($community->id, $id);

        \Session::flash('message', 'Gift deleted successfully.');

        return redirect($this->community->present()->url('managegifts'));
    }

    public function cashoutRequests()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        $community = $this->community;

        $cashout_requests = $this->giftsCashoutRepository()->getRequests($community->id);

        return $this->render('community.pannel.gifts.cashout_requests', ['cashout_requests' => $cashout_requests], [
            'title' => $this->setTitle('Pages'),
        ]);
    }

    public function cashGivenUpdate(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $id = $request->get('id');
        $val = $request->get('val');
        $cash_note = $request->get('cash_note');
        $transfer_type = $request->get('transfer_type');
        $transaction_id = $request->get('transaction_id');
        $transfer_date = $request->get('transfer_date');

        return $this->giftsCashoutRepository()->cashGivenUpdate($community, $id, $val, $cash_note, $transfer_type, $transaction_id, $transfer_date);
    }

    public function giftCashoutDownload()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $columnNames = ['User Name', 'Amount', 'Request Date', 'Cash Given', 'Cashout Date', 'Note', 'Bank Account Name', 'Transit Number', 'Institute Number', 'Account Number', 'Bank Name', 'Bank Address', 'Etransfer', 'Transfer Type', 'Reference id'];
        $array_data[] = $columnNames;

        $cashoutRequests = $this->giftsCashoutRepository()->getAllRequests($community->id);

        foreach ($cashoutRequests as $data) {
            $dataCollected = [];
            if ($data->user) {
                array_push($dataCollected, $data->user->fullname);
            } else {
                array_push($dataCollected, '');
            }

            array_push($dataCollected, number_format((float) $data->amount, 2, '.', ''));
            array_push($dataCollected, $data->request_date);

            if ($data->status == 0) {
                array_push($dataCollected, 'Not Paid');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
            } else {
                array_push($dataCollected, 'Paid');
                array_push($dataCollected, $data->cashout_date);
                array_push($dataCollected, $data->note);
            }

            $bank_details = $this->giftsBankDetailsRepository()->getById($community->id, $data->user->id);
            if ($bank_details) {
                array_push($dataCollected, $bank_details->account_name);
                array_push($dataCollected, $bank_details->transit_number);
                array_push($dataCollected, $bank_details->institute_number);
                array_push($dataCollected, $bank_details->account_number);
                array_push($dataCollected, $bank_details->bank_name);
                array_push($dataCollected, $bank_details->bank_address);
                array_push($dataCollected, $bank_details->etransfer_email);
            } else {
                array_push($dataCollected, '');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
                array_push($dataCollected, '');
            }

            if ($data->transfer_type == 1 and $data->status == 1) {
                array_push($dataCollected, 'Bank Transfer');
            } elseif ($data->transfer_type == 2 and $data->status == 1) {
                array_push($dataCollected, 'Interac Transfer');
            } else {
                array_push($dataCollected, '');
            }

            if ($data->transfer_type == 1 and $data->status == 1) {
                array_push($dataCollected, $data->transaction_id);
            } elseif ($data->transfer_type == 2 and $data->status == 1) {
                array_push($dataCollected, $data->transaction_id);
            } else {
                array_push($dataCollected, '');
            }

            $array_data[] = $dataCollected;
        }

        $excelFileName = 'Cashout-Requests';
        $this->exportAsExcel($array_data, $excelFileName);
    }

    public function paymentSettings(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        if ($community->take_payment_in_own_account == 0 and $community->take_community_payment_in_own_account == 0) {
            return redirect($community->present()->url());
        }

        $payment_settings = $this->communityPaymentSettingRepository()->getByCmId($this->community->id);

        $message = '';
        if ($val = $request->get('val')) {

            $payment_settings = $this->communityPaymentSettingRepository()->save($val, $this->community->id);

            $message = 'Payment details saved succefully';
        }

        return $this->render('community.pannel.cms.payment-settings', ['community' => $community, 'payment_settings' => $payment_settings, 'message' => $message], [
            'title' => $this->setTitle('Payment Details'),
        ]);
    }

    public function manageAdvertisements()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        $ads = $this->communityAdvertisementsRepository()->getByCommunityId($community->id);
        $message = '';

        return $this->render('community.pannel.advertisements.index', ['community' => $community, 'ads' => $ads, 'message' => $message], [
            'title' => $this->setTitle('Advertisements'),
        ]);
    }

    public function addAdvertisement(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $ad = $this->communityAdvertisementsRepository()->save($val, $community->id);
            if ($ad) {
                \Session::flash('success', 'Advertisement created successfully.');

                return redirect($community->present()->url('advertisements/manage'));
            } else {
                \Session::flash('success', 'Something went wrong.');

                return redirect($community->present()->url('advertisements/add'));
            }
        }

        return $this->render('community.pannel.advertisements.add', ['community' => $community], [
            'title' => $this->setTitle('Add Advertisement'),
        ]);
    }

    public function editMyAdvertisement($slug, $adid)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        $ad = $this->communityAdvertisementsRepository()->getByIdCommunityId($community->id, $adid);

        if ($val = $request->get('val')) {
            $ad = $this->communityAdvertisementsRepository()->edit($val, $community->id, $ad);
            if ($ad) {
                \Session::flash('success', 'Advertisement edited successfully.');

                return redirect($community->present()->url('advertisements/manage'));
            } else {
                \Session::flash('success', 'Something went wrong.');

                return redirect($community->present()->url('advertisements/manage'));
            }
        }

        if ($ad) {
            return $this->render('community.pannel.advertisements.edit', ['community' => $community, 'ad' => $ad], [
                'title' => $this->setTitle('Edit Advertisement'),
            ]);
        }

        \Session::flash('success', 'Invalid request.');

        return redirect(\URL::previous());
    }

    public function deleteMyAdvertisement($slug, $adid)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        $this->communityAdvertisementsRepository()->deleteByCommunityId($community->id, $adid);
        \Session::flash('success', 'Advertisement deleted successfully.');

        return redirect(\URL::previous());
    }

    public function advertisementPause($slug, $adid)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        $this->communityAdvertisementsRepository()->pauseByCommunityId($community->id, $adid);
        \Session::flash('success', 'Advertisement paused successfully.');

        return redirect(\URL::previous());
    }

    public function advertisementResume($slug, $adid)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($community->activate_advertisement == 0) {
            return redirect($community->present()->url());
        }

        $this->communityAdvertisementsRepository()->resumeByCommunityId($community->id, $adid);
        \Session::flash('success', 'Advertisement resumed successfully.');

        return redirect(\URL::previous());
    }

    public function communityBankDetails(Request $request)
    {
        $community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $this->giftsBankDetailsRepository()->addBankDetails($val, $community->id, 0);

            $user_money_transfer_option = $request->get('user_money_transfer_option');
            $community->user_money_transfer_option = $user_money_transfer_option;
            $community->save();

            \Session::flash('message', trans('internal-collaborations.bank-details-added-successfully'));

            return redirect($this->community->present()->url('communitybankdetails'));
        }

        $bank_details = $this->giftsBankDetailsRepository()->getById($community->id, 0);

        return $this->render('community.pannel.gifts.bank-details', ['community' => $community, 'bank_details' => $bank_details], [
            'title' => $this->setTitle(trans('internal-collaborations.bank-details')),
        ]);
    }
	
	public function communityWallet(Request $request)
    {
		$community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

        [$account, $transactions] = $this->communityAccountRepository()->getSummary($communityId, 20);

        // Preload tracking numbers for label-related transactions.
        // Tracking is stored on business_products_orders_details.tracking_number.
        $trackingByDetailId = [];
        $trackingByOrderId = [];
        try {
            $detailIds = [];
            $orderIds = [];
            if ($transactions && $transactions->count() > 0) {
                foreach ($transactions as $tx) {
                    $type = (string) ($tx->type ?? '');
                    if ($type !== 'label' && $type !== 'label_created' && $type !== 'label_refund') {
                        continue;
                    }
                    $detailId = (int) ($tx->order_detail_id ?? ($tx->detail_id ?? 0));
                    if ($detailId > 0) {
                        $detailIds[] = $detailId;
                    }

                    $orderId = trim((string) ($tx->order_id ?? ''));
                    if ($orderId === '' && $type !== 'label_created') {
                        $orderId = trim((string) ($tx->type_id ?? ''));
                    }
                    if ($orderId !== '' && $orderId !== '2147483647') {
                        $orderIds[] = $orderId;
                    }
                }
            }
            $detailIds = array_values(array_unique($detailIds));
            if ($detailIds) {
                $trackingByDetailId = \App\Models\BusinessProductsOrdersDetails::query()
                    ->whereIn('id', $detailIds)
                    ->pluck('tracking_number', 'id')
                    ->toArray();
            }

            $orderIds = array_values(array_unique($orderIds));
            if ($orderIds) {
                $trackingByOrderId = \App\Models\BusinessProductsOrders::query()
                    ->whereIn('order_id', $orderIds)
                    ->pluck('tracking_number', 'order_id')
                    ->toArray();
            }
        } catch (\Throwable $e) {
            $trackingByDetailId = [];
            $trackingByOrderId = [];
        }

        return $this->render('community.pannel.wallet.index', [
            'pageName' => 'account',
            'account' => $account,
            'transactions' => $transactions,
            'trackingByDetailId' => $trackingByDetailId,
            'trackingByOrderId' => $trackingByOrderId,
        ]);
    }
	
	
	public function communityCoupons(Request $request)
    {
		$community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

        [$account, $transactions] = $this->communityAccountRepository()->getSummary($communityId, 20);
		
		$current_balance=0;
		
		if($account){
			$current_balance=$account->current_balance;
		}
		
		 if ($val = $request->get('val')) {
          
		  	$coupon_total_amount=$val['coupon_total_amount'];
		  	if($coupon_total_amount > $current_balance){
				\Session::flash('error_message', "Insufficient balance to generate coupons");
			}else{
				$message=$this->communityCouponsBatchesRepository()->addBatch($val,$communityId);
				\Session::flash('success_message', $message);
			}
			
            return redirect($this->community->present()->url('communitycoupons'));
        }
		
        return $this->render('community.pannel.coupons.index', [
			'account' => $account,
			'current_balance'=>$current_balance,
            'transactions' => $transactions,
        ]);
    }
	
	public function communityCouponCreate(Request $request)
    {
		$community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

        $val = $request->get('val');
          
		$message=$this->communityCouponsBatchesRepository()->addBatchPercent($val,$communityId);
		\Session::flash('success_message', $message);
	
	    return redirect($this->community->present()->url('communitycoupons'));
    }
	
	public function communityCouponsBatches(Request $request)
    {
		$community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

		$batches=$this->communityCouponsBatchesRepository()->getBatchesByCommunityId($communityId);
		
        return $this->render('community.pannel.coupons.batches', [
			'batches' => $batches,
        ]);
    }
	
	public function communityCouponsList(Request $request)
    {
		$community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

		$batchid = $request->get('batchid');
		$type = $request->get('type');
		$coupon_batch='';
		if($batchid > 0){
			$coupon_batch=$this->communityCouponsBatchesRepository()->getByCommunityId($communityId,$batchid);
		}
		
		$coupons=$this->communityCouponsRepository()->getCouponsByCommunityId($communityId,$batchid,$type);
		
        return $this->render('community.pannel.coupons.list', [
			'coupons' => $coupons,
			'coupon_batch'=>$coupon_batch,
        ]);
    }
	
	
	public function communityWalletTopup(Request $request)
    {
        $community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $communityUserId = (int) (\Auth::user()->id ?? 0);
        $communityId = $community->id;

        if ($request->isMethod('post')) {

            // Minimum topup amount (configured in AdminCP ? configurations/topup-settings).
            $minTopupAmount = 0.01;
            try {
                $defaultRaw = '10';
                try {
                    $file = config_path('site/topup-settings.php');
                    if (is_string($file) && $file !== '' && file_exists($file)) {
                        $cfg = include $file;
                        if (is_array($cfg) && isset($cfg['topup-minimum-amount']['value'])) {
                            $defaultRaw = (string) $cfg['topup-minimum-amount']['value'];
                        }
                    }
                } catch (\Throwable $e) {
                    // ignore
                }

                $raw = $defaultRaw;
                try {
                    $raw = app('App\\Repositories\\ConfigurationRepository')->get('topup-minimum-amount', $defaultRaw);
                } catch (\Throwable $e) {
                    $raw = $defaultRaw;
                }

                $min = (float) preg_replace('/[^0-9.\-]/', '', (string) $raw);
                if (is_finite($min) && $min > 0) {
                    $minTopupAmount = round($min, 2);
                }
            } catch (\Throwable $e) {
                $minTopupAmount = 0.01;
            }

            $validator = \Validator::make($request->all(), [
                'topup_amount' => 'required|numeric|min:' . (string) $minTopupAmount,
            ]);

            $coupon_applied = (int) $request->get('coupon_applied', 0);
            $coupon_code_applied = trim((string) $request->get('coupon_code_applied', ''));
            $coupon_discounted_price = (float) preg_replace('/[^0-9.\-]/', '', (string) $request->get('coupon_discounted_price', '0'));
            $discount_price = (float) preg_replace('/[^0-9.\-]/', '', (string) $request->get('discount_price', '0'));
            $coupon_discount_percentage = (float) preg_replace('/[^0-9.\-]/', '', (string) $request->get('coupon_discount_percentage', '0'));

            if ($coupon_applied !== 1 || $coupon_code_applied === '') {
                $coupon_applied = 0;
                $coupon_code_applied = '';
                $coupon_discounted_price = 0;
                $discount_price = 0;
                $coupon_discount_percentage = 0;
            }

            $isZeroPayByCoupon = $coupon_applied === 1 && $coupon_discounted_price <= 0;
            if (! $isZeroPayByCoupon) {
                $validator->sometimes('stripeToken', 'required|string', function () {
                    return true;
                });
            }

            if ($validator->fails()) {
                return redirect($community->present()->url('communitywallettopup'))
                    ->withErrors($validator)
                    ->withInput();
            }

            $amount = round((float) $request->get('topup_amount'), 2);

            $stripeToken = (string) $request->get('stripeToken');
            $setAsDefault = (int) $request->get('set_as_default', 0) === 1;

            if ($coupon_discounted_price > $amount) {
                $coupon_discounted_price = $amount;
            }
            if ($discount_price > $amount) {
                $discount_price = $amount;
            }

            $payableAmount = $amount;
            if ($coupon_applied === 1) {
                $payableAmount = round(max($coupon_discounted_price, 0), 2);
            }

            if ($isZeroPayByCoupon) {
                $txMeta = [
                    'payment_gateway' => 'coupon',
                    'payment_status' => 'succeeded',
                    'currency' => 'usd',
                    'coupon_applied' => 1,
                    'coupon_code' => $coupon_code_applied,
                    'discount_percentage' => $coupon_discount_percentage,
                    'discount_price' => $discount_price,
                    'net_paid' => 0,
                    'stripe_charge_id' => 'coupon_zero_' . uniqid('', true),
                ];

                $topupResult = $this->communityAccountRepository()->topUp($communityUserId, $communityId, $amount, $txMeta);
                $topupTxId = 0;
                if (is_array($topupResult) && isset($topupResult[1]) && ! empty($topupResult[1])) {
                    $topupTxId = (int) ($topupResult[1]->id ?? 0);
                }
                if ($coupon_code_applied !== '') {
                    try {
                        app('App\\Repositories\\CommunityCouponsRepository')->updateCouponStatus($coupon_code_applied, (int) (\Auth::id() ?? 0), 'community_wallet_topup', $topupTxId);
                    } catch (\Throwable $e) {
                        // ignore coupon status update failures
                    }
                }

                return redirect($community->present()->url('communitywallet'))
                    ->with('message', trans('businessecommerce.topup-success'));
            }

            // Use store/community Stripe keys if the storefront takes payments in its own Stripe account.
            $stripeSecretKey = (string) config('stripe_secret_key');
            $stripePublishableKey = (string) config('stripe_publishable_key');

            try {
                \Stripe\Stripe::setApiKey($stripeSecretKey);

                $storeTitle = trim((string) ($community->title ?? ''));
                if ($storeTitle === '') {
                    $storeTitle = 'Community';
                }
                $stripeTopupDescription = $storeTitle . ' - Community account top up';

                $payer = \Auth::user();
                $payerUserId = (int) (\Auth::id() ?? 0);

                $cardBrand = null;
                $cardCountry = null;
                $cardLast4 = null;
                $cardExpMonth = null;
                $cardExpYear = null;

                try {
                    $stripeTokenObject = \Stripe\Token::retrieve($stripeToken);
                    if (! empty($stripeTokenObject) && ! empty($stripeTokenObject->card)) {
                        $cardBrand = $stripeTokenObject->card->brand ?? null;
                        $cardCountry = $stripeTokenObject->card->country ?? null;
                        $cardLast4 = $stripeTokenObject->card->last4 ?? null;
                        $cardExpMonth = $stripeTokenObject->card->exp_month ?? null;
                        $cardExpYear = $stripeTokenObject->card->exp_year ?? null;
                    }
                } catch (\Stripe\Exception\ApiErrorException $e) {
                    throw new \Exception($e->getMessage());
                }

                // Calculate charge from coupon-adjusted payable, but credit from original topup amount.
                $chargeBaseCents = (int) round($payableAmount * 100);
                $creditBaseCents = (int) round($amount * 100);
                $fee = null;
                $creditFee = null;
                $amountToChargeCents = $chargeBaseCents;
                $amountToCredit = round($creditBaseCents / 100, 2);
                try {
                    $calculator = app('App\\Services\\TopupTransactionFeeCalculator');
                    $sellerCountry = '';
                    $fee = $calculator->calculateCents($chargeBaseCents, $cardBrand, $cardCountry, $sellerCountry);
                    $creditFee = $calculator->calculateCents($creditBaseCents, $cardBrand, $cardCountry, $sellerCountry);

                    if (is_array($fee) && isset($fee['amount_to_charge_cents'])) {
                        $amountToChargeCents = (int) $fee['amount_to_charge_cents'];
                    }
                    if (is_array($creditFee) && isset($creditFee['amount_to_credit_cents'])) {
                        $amountToCredit = round(((int) $creditFee['amount_to_credit_cents']) / 100, 2);
                    }
                } catch (\Throwable $e) {
                    // If fee calc fails, fall back to payable for charge and original for credit.
                    $fee = null;
                    $creditFee = null;
                    $amountToChargeCents = $chargeBaseCents;
                    $amountToCredit = $amount;
                }

                if ($amountToCredit <= 0) {
                    throw new \Exception('Top up amount is too low after fees.');
                }

                $stripeCustomerId = null;
                try {
                    $stripeCustomerId = (string) ($payer->thridparty_stripe_customer_id ?? '');
                } catch (\Throwable $e) {
                    $stripeCustomerId = '';
                }

                $stripeSourceId = null;
                if (! $stripeCustomerId) {
                    $customer = \Stripe\Customer::create([
                        'name' => trim((string) ($payer->name ?? '')),
                        'email' => (string) ($payer->email ?? ''),
                        'description' => $stripeTopupDescription,
                        'source' => $stripeToken,
                    ]);

                    $stripeCustomerId = (string) ($customer->id ?? '');
                    try {
                        $payer->thridparty_stripe_customer_id = $stripeCustomerId;
                        $payer->save();
                    } catch (\Throwable $e) {
                        // ignore save failures
                    }

                    $stripeSourceId = (string) ($customer->default_source ?? '');
                    if (! $stripeSourceId && ! empty($customer->sources) && ! empty($customer->sources->data) && ! empty($customer->sources->data[0])) {
                        $stripeSourceId = (string) ($customer->sources->data[0]->id ?? '');
                    }
                } else {
                    // Attach token to customer and use it for this charge.
                    $source = \Stripe\Customer::createSource($stripeCustomerId, ['source' => $stripeToken]);
                    $stripeSourceId = (string) ($source->id ?? '');
                }

                $currency = 'usd';
               /* try {
                    $pageCurrency = (string) ($this->page->currency ?? '');
                    $pageCurrency = strtolower(trim($pageCurrency));
                    if ($pageCurrency !== '') {
                        // Stripe expects lowercase ISO currency.
                        $currency = $pageCurrency;
                    }
                } catch (\Throwable $e) {
                    $currency = 'usd';
                }*/

                $charge = \Stripe\Charge::create([
                    'customer' => $stripeCustomerId,
                    'source' => $stripeSourceId ?: $stripeToken,
                    'amount' => $amountToChargeCents,
                    'currency' => $currency,
                    'description' => $stripeTopupDescription,
                    'metadata' => [
                        'community_id' => $communityId,
                        'community_user_id' => $communityUserId,
                        'payer_user_id' => $payerUserId,
                    ],
                ]);

                $chargeData = $charge ? $charge->jsonSerialize() : [];
                $paid = (bool) ($chargeData['paid'] ?? false);
                $captured = (bool) ($chargeData['captured'] ?? false);
                $failureCode = $chargeData['failure_code'] ?? null;
                if (! $paid || ! $captured || ! empty($failureCode)) {
                    throw new \Exception('Payment failed.');
                }

                // Save card by payer user and enforce one default per user.
                if ($payerUserId > 0 && $stripeSourceId) {
                    $this->accountPaymentCardRepository()->upsertStripeCardCommunity($communityId, [
                        'stripe_customer_id' => $stripeCustomerId,
                        'stripe_source_id' => $stripeSourceId,
                        'card_brand' => $cardBrand,
                        'card_country' => $cardCountry,
                        'card_last4' => $cardLast4,
                        'card_exp_month' => $cardExpMonth,
                        'card_exp_year' => $cardExpYear,
                        'set_as_default' => $setAsDefault ? 1 : 0,
                    ]);
                }

                $txMeta = [
                    'payment_gateway' => 'stripe',
                    'payment_status' => (string) ($chargeData['status'] ?? 'succeeded'),
                    'currency' => $currency,
                    'stripe_charge_id' => $chargeData['id'] ?? null,
                    'stripe_balance_transaction_id' => $chargeData['balance_transaction'] ?? null,
                    'stripe_customer_id' => $stripeCustomerId,
                    'stripe_source_id' => $stripeSourceId,
                    'card_brand' => $cardBrand,
                    'card_country' => $cardCountry,
                    'card_last4' => $cardLast4,
                    'card_exp_month' => $cardExpMonth,
                    'card_exp_year' => $cardExpYear,
                    'receipt_url' => null,
                    'coupon_applied' => $coupon_applied,
                    'coupon_code' => $coupon_code_applied,
                    'discount_percentage' => $coupon_discount_percentage,
                    'discount_price' => $discount_price,
                    'net_paid' => round(((float) $amountToChargeCents) / 100, 2),
                ];

                // Optional fee metadata (stored only if columns exist).
                if (is_array($fee)) {
                    $txMeta['topup_fee_method'] = $fee['method'] ?? null;
                    $txMeta['topup_fee_percent'] = $fee['base_percent'] ?? $fee['percent'] ?? null;
                    $txMeta['topup_effective_percent'] = $fee['effective_percent'] ?? $fee['percent'] ?? null;
                    $txMeta['topup_fee_fixed'] = $fee['fixed'] ?? null;
                    $txMeta['topup_is_international'] = $fee['is_international'] ?? null;
                    $txMeta['topup_international_uplift_percent'] = $fee['international_uplift_percent'] ?? null;
                    $txMeta['service_fee_cents'] = $fee['service_fee_cents'] ?? null;
                    $txMeta['base_service_fee_cents'] = $fee['base_service_fee_cents'] ?? null;
                    $txMeta['international_fee_cents'] = $fee['international_fee_cents'] ?? null;
                    $txMeta['amount_to_charge_cents'] = $fee['amount_to_charge_cents'] ?? null;
                    $txMeta['amount_to_credit_cents'] = is_array($creditFee) ? ($creditFee['amount_to_credit_cents'] ?? null) : null;
                }

                // If expanded charges are enabled in your Stripe version, receipt_url may exist.
                try {
                    if (! empty($charge->receipt_url)) {
                        $txMeta['receipt_url'] = (string) $charge->receipt_url;
                    }
                } catch (\Throwable $e) {
                    // ignore
                }

                $topupResult = $this->communityAccountRepository()->topUp($communityUserId, $communityId, $amountToCredit, $txMeta);
                $topupTxId = 0;
                if (is_array($topupResult) && isset($topupResult[1]) && ! empty($topupResult[1])) {
                    $topupTxId = (int) ($topupResult[1]->id ?? 0);
                }
                if ($coupon_applied === 1 && $coupon_code_applied !== '') {
                    try {
                        app('App\\Repositories\\CommunityCouponsRepository')->updateCouponStatus($coupon_code_applied, (int) (\Auth::id() ?? 0), 'community_wallet_topup', $topupTxId);
                    } catch (\Throwable $e) {
                        // ignore coupon status update failures
                    }
                }

                return redirect($community->present()->url('communitywallet'))
                    ->with('message', trans('businessecommerce.topup-success'));
            } catch (\Throwable $e) {
                return redirect($community->present()->url('communitywallettopup'))
                    ->with('error', $e->getMessage());
            }
        }

        $account = $this->accountDetailRepository()->getOrCreateByCommunityId($community->id);

        return $this->render('community.pannel.wallet.topup', [
            'pageName' => 'account',
            'account' => $account,
        ]);
    }

    public function userPaymentsDashboard()
    {
        $community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }
        $ecom_user_ids = $this->businessProductsOrdersRepository()->getBusinessPaymentsUsersByCm($community->id);
        $events_user_ids = $this->postEventsPaymentRepository()->getEventsPaymentsUsersByCm($community->id);

        $all_user_ids = array_unique(array_merge($events_user_ids, $ecom_user_ids));

        $users = $this->userRepository()->getPaymentsUsersByIds($all_user_ids);

        return $this->render('community.pannel.payments.user-payments', ['community' => $community, 'users' => $users], [
            'title' => $this->setTitle('Users Payment Dashboard'),
        ]);
    }

    public function userEcommercePayments($slug)
    {
        $community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $orders = $this->businessProductsOrdersRepository()->getProductPaymentsByUserCm($community->id);

        return $this->render('community.pannel.payments.users-ecommerce-payments', ['community' => $community, 'orders' => $orders], [
            'title' => $this->setTitle('Users Ecommerce Payments'),
        ]);
    }

    public function userEventsPayments($slug)
    {
        $community = $this->community;

        if (! ($community->isOwner())) {
            return redirect($community->present()->url());
        }

        $events_payment = $this->postEventsPaymentRepository()->getEventsPaymentsByCm($community->id);

        return $this->render('community.pannel.payments.users-events-payments', ['community' => $community, 'events_payment' => $events_payment], [
            'title' => $this->setTitle('Users Events and Crowdfunding Payments'),
        ]);
    }

    public function communityMembers()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        /*$transactions=$this->giftsTransactionsRepository()->getAllByCommunityId($community->id);
        foreach($transactions as $trns){
            $this->communityVisitorsRepository()->addVisitor($trns->from_userid,$community->id);
            $this->communityVisitorsRepository()->addVisitor($trns->to_userid,$community->id);
        }*/

        $members = $this->communityVisitorsRepository()->getByCommunityId($community->id);

        return $this->render('community.pannel.gifts.visiting-members', ['community' => $community, 'members' => $members], [
            'title' => $this->setTitle('Members'),
        ]);
    }

    public function communityVisitorAction($slug, $mid, $action)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $member = $this->communityVisitorsRepository()->findByIdCid($mid, $community->id);
        if ($member) {
            $member->is_suspended = $action;
            $member->save();
        }

        return redirect(\URL::previous());
    }

    public function userGiftAccount($slug, $uid)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $selected_user = $this->userRepository()->getById($uid);

        $user_account = $this->giftsAccountRepository()->getByUserIdCmId($community->id, $uid);

        return $this->render('community.pannel.gifts.members-account', ['community' => $community, 'user_account' => $user_account, 'selected_user' => $selected_user], [
            'title' => $this->setTitle('Members'),
        ]);
    }

    public function userGiftsPurchased($slug, $uid)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $selected_user = $this->userRepository()->getById($uid);

        $gifts = $this->giftsRepository()->myGifts($community->id, $uid);

        return $this->render('community.pannel.gifts.members-gifts', ['community' => $community, 'gifts' => $gifts, 'selected_user' => $selected_user], [
            'title' => $this->setTitle('Members'),
        ]);
    }

    public function racingDashboard()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        return $this->render('community.pannel.racing.index', ['community' => $community], [
            'title' => $this->setTitle('Racing Dashboard'),
        ]);
    }

    public function createSlots(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $slot = $this->communityRideTimeslotsRepository()->add($val, $community);
            if ($slot) {
                \Session::flash('message', 'Slot added successfully');

                return redirect($this->community->present()->url('rideslotslist'));
            } else {
                \Session::flash('message', 'Slot already exist');

                return redirect($this->community->present()->url('createslots'));
            }
        }

        return $this->render('community.pannel.racing.create-time-slots', ['community' => $community], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function rideSlotsList()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $slots = $this->communityRideTimeslotsRepository()->getSlotsUser($community->id, \Auth::user()->id);

        return $this->render('community.pannel.racing.time-slots-list', ['community' => $community, 'slots' => $slots], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function createLocation(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $location = $this->communityRideLocationsRepository()->add($val, $community);
            if ($location) {
                \Session::flash('message', 'Location added successfully');

                return redirect($this->community->present()->url('ridelocationslist'));
            } else {
                \Session::flash('message', 'Location already exist.');

                return redirect($this->community->present()->url('createlocation'));
            }
        }

        // $slots=$this->communityRideTimeslotsRepository()->getAllSlots($community->id);

        return $this->render('community.pannel.racing.create-locations', ['community' => $community], [
            'title' => $this->setTitle('Racing Create Locations'),
        ]);
    }

    public function rideLocationsList()
    {
        $community = $this->community;
        $locations = $this->communityRideLocationsRepository()->getLocations($community->id);

        return $this->render('community.pannel.racing.locations-list', ['community' => $community, 'locations' => $locations], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function createSims(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $sim = $this->communityRideSimsRepository()->add($val, $community);
            if ($sim) {
                \Session::flash('message', 'SIM attached successfully');

                return redirect($this->community->present()->url('ridesimlist'));
            } else {
                \Session::flash('message', 'SIM already attached');

                return redirect($this->community->present()->url('createsims'));
            }
        }

        $locations = $this->communityRideLocationsRepository()->getAllLocations($community->id);
        $sims = $this->communityRideSimsRepository()->getAllSIMsParent($community->id);

        return $this->render('community.pannel.racing.create-sims', ['community' => $community, 'locations' => $locations, 'sims' => $sims], [
            'title' => $this->setTitle('Racing Create SIMs'),
        ]);
    }

    public function addSim(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $sim = $this->communityRideSimsRepository()->addSim($val, $community);
            if ($sim) {
                \Session::flash('message', 'SIM added successfully');

                return redirect($this->community->present()->url('ridesims'));
            } else {
                \Session::flash('message', 'SIM already exist');

                return redirect($this->community->present()->url('addsim'));
            }
        }

        return $this->render('community.pannel.racing.add-sim', ['community' => $community], [
            'title' => $this->setTitle('Racing Create SIMs'),
        ]);
    }

    public function rideSimList(Request $request)
    {
        $location_id = $request->get('type');
        $community = $this->community;

        $locations_list = '';
        $sims = '';

        if ($location_id) {

            $getAllSIMs = $this->communityRideSimsRepository()->getUserAllSIMsNotLocation($community->id, $location_id, \Auth::user()->id);

            if ($getAllSIMs) {
                foreach ($getAllSIMs as $sm) {
                    $smAdded = $this->communityRideSimsRepository()->getByLocationId($community->id, $location_id, $sm);
                    if (! $smAdded) {
                        $val = [
                            'location_id' => $location_id,
                            'sim' => $sm,
                        ];
                        $this->communityRideSimsRepository()->add($val, $community);
                    }
                }
            }

            $sims = $this->communityRideSimsRepository()->getSIMs($community->id, $location_id);

        } else {
            $locations_list = $this->communityRideLocationsRepository()->getUserLocations($community->id, \Auth::user()->id);
        }

        $locations = $this->communityRideLocationsRepository()->getUserAllLocations($community->id, \Auth::user()->id);

        $location = $this->communityRideLocationsRepository()->getById($community->id, $location_id);

        return $this->render('community.pannel.racing.sim-list', ['community' => $community, 'sims' => $sims, 'locations' => $locations, 'location_id' => $location_id, 'location' => $location, 'locations_list' => $locations_list], ['title' => $this->setTitle('Racing Create Costs')]);
    }

    public function rideSimListParent()
    {
        $community = $this->community;
        $sims = $this->communityRideSimsRepository()->getUserSIMsParent($community->id, \Auth::user()->id);

        return $this->render('community.pannel.racing.sim-list-parent', ['community' => $community, 'sims' => $sims], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function createCosts()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        return $this->render('community.pannel.racing.create-costs', ['community' => $community], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function rideDeleteTimeSlot($slug, $id)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $this->communityRideTimeslotsRepository()->deleteByIdUser($community->id, $id);
        \Session::flash('message', 'Slot deleted successfully');

        return redirect($this->community->present()->url('rideslotslist'));
    }

    public function rideDeleteLocation($slug, $id)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $this->communityRideLocationsRepository()->deleteById($community->id, $id);
        \Session::flash('message', 'Location deleted successfully');

        return redirect($this->community->present()->url('ridelocationslist'));
    }

    public function rideDeleteSim($slug, $id)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $this->communityRideSimsRepository()->deleteById($community->id, $id);
        \Session::flash('message', 'SIM attached deleted successfully');

        return redirect($this->community->present()->url('ridesimlist'));
    }

    public function rideDeleteSimParent($slug, $id)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $this->communityRideSimsRepository()->deleteById($community->id, $id);
        \Session::flash('message', 'SIM deleted successfully');

        return redirect($this->community->present()->url('ridesims'));
    }

    public function rideDeleteCorporateSimParent($slug, $id)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $this->communityRideSimsRepository()->deleteById($community->id, $id);
        \Session::flash('message', 'SIM deleted successfully');

        return redirect($this->community->present()->url('ridecorporatesims'));
    }

    public function rideDefineSimCost($slug, $id,Request $request)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $sim = $this->communityRideSimsRepository()->getById($community->id, $id);

        $slots = $this->communityRideTimeslotsRepository()->getAllSlotsByUser($community->id, \Auth::user()->id);

        if ($request->get('val') || $request->get('avail')) {
            $this->communityRideCostsRepository()->add($request->get('val'), $request->get('avail'), $sim, $community->id, $request->get('val_student'), $request->get('avail_student'));

            \Session::flash('message', 'Cost saved successfully');

            return redirect($this->community->present()->url('ridedefinesimcost').'/'.$id);
        }

        if ($sim and $sim->is_deleted == 0) {
            return $this->render('community.pannel.racing.define-cost', ['community' => $community, 'sim' => $sim, 'slots' => $slots], [
                'title' => $this->setTitle('Racing Define Costs'),
            ]);
        }

        return redirect($community->present()->url());
    }

    public function rideBookingReport(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        // $records=$this->communityPricingPlanPaymentRepository()->getRidingPayments($community->id,$location_id);

        $records = $this->appointmentRepository()->getRidingBookings($community->id, $location_id);

        $locations = $this->communityRideLocationsRepository()->getAll($community->id);

        return $this->render('community.pannel.racing.booking-report', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Racing Define Costs'),
        ]);
    }

    public function rideBookingCancelled(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $records = $this->appointmentRepository()->getRidingBookingsCancelled($community->id, $location_id);

        $locations = $this->communityRideLocationsRepository()->getAll($community->id);

        return $this->render('community.pannel.racing.cancelled-booking-report', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Racing Define Costs'),
        ]);
    }

    public function rideBookingFailed(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $records = $this->communityPricingPlanPaymentRepository()->getRidingFailedPayments($community->id, $location_id);

        $locations = $this->communityRideLocationsRepository()->getAll($community->id);

        return $this->render('community.pannel.racing.failed-booking-report', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Racing Define Costs'),
        ]);
    }

    public function rideBookingReportExcel(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        // $records=$this->communityPricingPlanPaymentRepository()->getRidingPaymentsAll($community->id,$location_id);
        $records = $this->appointmentRepository()->getRidingBookingsAll($community->id, $location_id);

        $columnNames = ['User Name', 'Date and Time', 'Slot', 'Location', 'SIM', 'Amount Paid'];
        $array_data[] = $columnNames;

        foreach ($records as $data) {
            if ($data->ridetimeslot and $data->ridelocation and $data->ridesim) {
                $dataCollected = [];
                if ($data->user) {
                    array_push($dataCollected, $data->user->fullname);
                } else {
                    array_push($dataCollected, '');
                }

                array_push($dataCollected, $data->start_time);

                array_push($dataCollected, $data->ridetimeslot->times.' '.$data->ridetimeslot->name);

                array_push($dataCollected, $data->ridelocation->location);

                array_push($dataCollected, $data->ridesim->sim);

                $amount = '';
                if ($data->ridepayment and $data->ridepayment->amount != '0.00') {
                    $amount = '$'.number_format((float) $data->ridepayment->amount, 2, '.', '');

                }

                if ($data->ridepayment and $data->ridepayment->coupon_payment) {
                    if ($amount != '') {
                        $amount .= ' and coupon redeemed';
                    } else {
                        $amount = 'coupon redeemed';
                    }
                }

                array_push($dataCollected, $amount);

                $array_data[] = $dataCollected;
            }
        }

        $excelFileName = 'Booking_Report';
        $this->exportAsExcel($array_data, $excelFileName);
    }

    public function rideTimeSettings($slug, $id,Request $request)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $sim = $this->communityRideSimsRepository()->getById($community->id, $id);

        if ($sim and $sim->is_deleted == 0) {

            if ($val = $request->get('val')) {

                $setting = $this->appointmentAvailabilityRepository()->addRideCommunitySim($val, $community->id, $sim->location_id, $sim->id);

                \Session::flash('message', 'Time settings saved successfully');

                return redirect($this->community->present()->url('ridetimesettings').'/'.$id);
            }

            $setting = $this->appointmentAvailabilityRepository()->getByRideCommunitySim($community->id, $sim->location_id, $sim->id);

            return $this->render('community.pannel.racing.sim-time-availability', ['community' => $community, 'sim' => $sim, 'setting' => $setting], [
                'title' => $this->setTitle('Racing Time Settings'),
            ]);
        }

        return redirect($community->present()->url());
    }

    public function rideDefineCorporate($slug, $id,Request $request)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $location = $this->communityRideLocationsRepository()->getByIdCorporate($community->id, $id);

        if ($val = $request->get('val')) {

            $location = $this->communityRideLocationsRepository()->saveCorporate($val, $location);

            \Session::flash('message', 'Cost saved successfully');

            return redirect($this->community->present()->url('ridedefinecorporate').'/'.$id);
        }

        if ($location and $location->is_deleted == 0) {
            return $this->render('community.pannel.racing.corporate.define-corporate', ['community' => $community, 'location' => $location], [
                'title' => $this->setTitle('Racing Define Costs'),
            ]);
        }

        return redirect($community->present()->url());
    }

    public function rideCorporateAvailability($id,Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $sim = $this->communityRideSimsRepository()->getById($community->id, $id);

        if ($sim and $sim->is_deleted == 0) {
            $sim->available_for_corporate = $value;
            $sim->save();
        }

        return redirect($community->present()->url());
    }

    public function rideIndividualAvailability($id,Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $sim = $this->communityRideSimsRepository()->getById($community->id, $id);

        if ($sim and $sim->is_deleted == 0) {
            $sim->available_for_individual = $value;
            $sim->save();
        }

        return redirect($community->present()->url());
    }

    public function corporateRacingDashboard()
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        return $this->render('community.pannel.racing.corporate.index', ['community' => $community], [
            'title' => $this->setTitle('Corporate Racing Dashboard'),
        ]);
    }

    public function corprateRideLocationslist()
    {
        $community = $this->community;
        $locations = $this->communityRideLocationsRepository()->getCorporateLocations($community->id);

        return $this->render('community.pannel.racing.corporate.locations-list', ['community' => $community, 'locations' => $locations], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function createCorporateLocation(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $location = $this->communityRideLocationsRepository()->addCorporate($val, $community);
            if ($location) {
                \Session::flash('message', 'Location added successfully');

                return redirect($this->community->present()->url('corprateridelocationslist'));
            } else {
                \Session::flash('message', 'Location already exist.');

                return redirect($this->community->present()->url('createcorporatelocation'));
            }
        }

        return $this->render('community.pannel.racing.corporate.create-locations', ['community' => $community], [
            'title' => $this->setTitle('Racing Create Locations'),
        ]);
    }

    public function corporateRideDeleteLocation($slug, $id)
    {
        $community = $this->community;
        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }
        $this->communityRideLocationsRepository()->deleteById($community->id, $id);
        \Session::flash('message', 'Location deleted successfully');

        return redirect($this->community->present()->url('corprateridelocationslist'));
    }

    public function rideCorporateSimListParent()
    {
        $community = $this->community;
        $sims = $this->communityRideSimsRepository()->getUserCorporateSIMsParent($community->id, \Auth::user()->id);

        return $this->render('community.pannel.racing.corporate.sim-list-parent', ['community' => $community, 'sims' => $sims], [
            'title' => $this->setTitle('Racing Create Costs'),
        ]);
    }

    public function addCorporateSim(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $sim = $this->communityRideSimsRepository()->addCorporateSim($val, $community);
            if ($sim) {
                \Session::flash('message', 'SIM added successfully');

                return redirect($this->community->present()->url('ridecorporatesims'));
            } else {
                \Session::flash('message', 'SIM already exist');

                return redirect($this->community->present()->url('addcorporatesim'));
            }
        }

        return $this->render('community.pannel.racing.corporate.add-sim', ['community' => $community], [
            'title' => $this->setTitle('Racing Create SIMs'),
        ]);
    }

    public function rideCorporateSimList(Request $request)
    {
        $community = $this->community;
        $location_id = $request->get('type');

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        // $sims=$this->communityRideSimsRepository()->getCorporateSIMs($community->id,$location_id);

        // $locations=$this->communityRideLocationsRepository()->getAllCorporateLocations($community->id);

        $locations_list = '';
        $sims = '';

        if ($location_id) {

            $getAllSIMs = $this->communityRideSimsRepository()->getUserAllSIMsNotLocation($community->id, $location_id, \Auth::user()->id);

            if ($getAllSIMs) {
                foreach ($getAllSIMs as $sm) {
                    $smAdded = $this->communityRideSimsRepository()->getByLocationId($community->id, $location_id, $sm);
                    if (! $smAdded) {
                        $val = [
                            'location_id' => $location_id,
                            'sim' => $sm,
                        ];
                        $this->communityRideSimsRepository()->add($val, $community);
                    }
                }
            }

            $sims = $this->communityRideSimsRepository()->getSIMs($community->id, $location_id);

        } else {
            $locations_list = $this->communityRideLocationsRepository()->getUserLocations($community->id, \Auth::user()->id);
        }

        $locations = $this->communityRideLocationsRepository()->getUserAllLocations($community->id, \Auth::user()->id);

        $location = $this->communityRideLocationsRepository()->getById($community->id, $location_id);

        return $this->render('community.pannel.racing.corporate.sim-list', ['community' => $community, 'sims' => $sims, 'locations' => $locations, 'location_id' => $location_id, 'location' => $location, 'locations_list' => $locations_list], [
            'title' => $this->setTitle('Corporate Product Configuration'),
        ]);
    }

    public function createCorporateSims(Request $request)
    {
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {
            $sim = $this->communityRideSimsRepository()->addCorporate($val, $community);
            if ($sim) {
                \Session::flash('message', 'SIM attached successfully');

                return redirect($this->community->present()->url('ridecorporatesimlist'));
            } else {
                \Session::flash('message', 'SIM already attached');

                return redirect($this->community->present()->url('createcorporatesims'));
            }
        }

        $locations = $this->communityRideLocationsRepository()->getAllCorporateLocations($community->id);
        $sims = $this->communityRideSimsRepository()->getAllCorporateSIMsParent($community->id);

        return $this->render('community.pannel.racing.corporate.create-sims', ['community' => $community, 'locations' => $locations, 'sims' => $sims], [
            'title' => $this->setTitle('Racing Create SIMs'),
        ]);
    }

    public function rideCorporateBookingReport(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $records = $this->appointmentRepository()->getCorporateRidingBookings($community->id, $location_id);

        $locations = $this->communityRideLocationsRepository()->getAllCorporate($community->id);

        return $this->render('community.pannel.racing.corporate.booking-report', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Racing Define Costs'),
        ]);
    }

    public function rideCorporateFailedBookingReport(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $records = $this->communityPricingPlanPaymentRepository()->getRidingFailedCorporatePayments($community->id, $location_id);

        $locations = $this->communityRideLocationsRepository()->getAllCorporate($community->id);

        return $this->render('community.pannel.racing.corporate.failed-booking-report', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Racing Define Costs'),
        ]);
    }

    public function rideCorporateBookingReportExcel(Request $request)
    {
        $location_id = $request->get('type');

        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $records = $this->appointmentRepository()->getCorporateRidingBookingsAll($community->id, $location_id);

        $columnNames = ['User Name', 'Date and Time', 'Duration', 'Location', 'SIMs', 'Amount Paid'];
        $array_data[] = $columnNames;

        foreach ($records as $data) {
            if ($data->ridelocation) {
                $dataCollected = [];
                if ($data->user) {
                    array_push($dataCollected, $data->user->fullname);
                } else {
                    array_push($dataCollected, '');
                }

                $times = 'From: '.$data->start_time.' to: '.$data->end_time;

                array_push($dataCollected, $times);

                $duration = $data->corporate_booking_type;
                if ($duration == 'firsthalf') {
                    $day = 'Half day - first half';
                } elseif ($duration == 'secondhalf') {
                    $day = 'Half day - second half';
                } else {
                    $day = 'Full day';
                }

                array_push($dataCollected, $day);

                array_push($dataCollected, $data->ridelocation->location);

                $sims = app('App\\Repositories\\AppointmentBookingRepository')->getAllCorporateBookingsSIMS($data->id);
                $simsList = '';

                if ($sims) {
                    foreach ($sims as $smid) {
                        $sm = $this->communityRideSimsRepository()->getById($community->id, $smid);
                        if ($sm) {
                            if ($simsList) {
                                $simsList = $simsList.', '.$sm->sim;
                            } else {
                                $simsList = $sm->sim;
                            }
                        }
                    }
                }

                array_push($dataCollected, $simsList);

                $amount = '';
                if ($data->ridepayment and $data->ridepayment->amount != '0.00') {
                    $amount = '$'.number_format((float) $data->ridepayment->amount, 2, '.', '');

                }

                if ($data->ridepayment and $data->ridepayment->coupon_payment) {
                    if ($amount != '') {
                        $amount .= ' and coupon redeemed';
                    } else {
                        $amount = 'coupon redeemed';
                    }
                }

                array_push($dataCollected, $amount);

                $array_data[] = $dataCollected;
            }
        }

        $excelFileName = 'Corporate_Booking_Report';
        $this->exportAsExcel($array_data, $excelFileName);
    }

    public function rideBookingStudentRequests(Request $request)
    {
        $location_id = $request->get('type');
        $community = $this->community;

        if (! ($community->present()->isAdminSubAdmin())) {
            return redirect($community->present()->url());
        }

        $locations_ids = $this->communityRideLocationsRepository()->getAllIdsByUser($community->id, \Auth::user()->id);

        $records = $this->communityRideStudentVerificationRepository()->getRequestsByLocations($community->id, $location_id, $locations_ids);
        $locations = $this->communityRideLocationsRepository()->getAllByUser($community->id, \Auth::user()->id);

        return $this->render('community.pannel.racing.students-requests', ['community' => $community, 'records' => $records, 'locations' => $locations, 'location_id' => $location_id], [
            'title' => $this->setTitle('Students Requests'),
        ]);
    }

    public function subscriptionInvoice($slug, $type, $type_id)
    {
        $community = $this->community;
        $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,
            'cards' => $cards,
        ], [
            'title' => $this->setTitle(trans('internal-collaborations.view-invoice')),
        ]);
    }

    public function spacePurchase()
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $community = $this->community;

        if ($community->present()->canAddExtraSpace()) {
            $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');
            $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);

            $plan = $community->present()->getPricingPlan($planDetails->plan_id);

            $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

            return $this->render('community.pannel.plan.space-purchase', ['cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card, 'plan' => $plan], [
                'title' => $this->setTitle('Space Purchase'),
            ]);
        }

        return redirect($community->present()->url());
    }

    public function payingForSpacePurchase(Request $request)
    {
        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $message = 'Something went wrong, try again later.';

        if (! empty($request->get('stripeToken')) || $request->get('default_card') == 1) {
            $number_of_users_in_plan = $request->get('number_of_users_in_plan');
            $paying_for_months = $request->get('paying_for_months');
            $amount_for_month = $request->get('amount_for_month');
            $paying_ttl_amnt = $request->get('paying_ttl_amnt');
            $stripeToken = $request->get('stripeToken');
            $currency_code = $request->get('currency_code');

            $payingAmount = $paying_ttl_amnt * 100;

            $has_default_card = $request->get('default_card');
            $orderId = rand(111111, 999999);

            $planDetails = $community->present()->getPricingPlan($community->pricing_plan);

            if ($payingAmount > 0) {

                // require_once app_path('library/stripe-php/init.php');
                $stripe = [
                    'secret_key' => config('stripe_secret_key'),
                    'publishable_key' => config('stripe_publishable_key'),
                ];

                \Stripe\Stripe::setApiKey($stripe['secret_key']);

                if ($has_default_card == 1) {
                    $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');
                    if ($default_card) {
                        $cardMessage = '';

                        try {
                            $payDetails = \Stripe\Charge::create([
                                'customer' => $default_card->customer_id,
                                'amount' => $payingAmount,
                                'currency' => $currency_code,
                                'description' => 'Space subscription',
                                'metadata' => [
                                    'order_id' => $orderId,
                                ],
                            ]);
                        } catch (\Stripe\Error\Base $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\Card $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\Authentication $e) {
                            $cardMessage = $e->getMessage();
                        } catch (\Stripe\Error\InvalidRequest $e) {
                            $cardMessage = $e->getMessage();
                        } catch (Exception $e) {
                            $cardMessage = $e->getMessage();
                        }

                        if ($cardMessage) {
                            \Session::flash('pay_error_msg', $cardMessage);

                            return redirect($this->community->present()->url('spacepurchase'));
                        }

                        $customerName = $community->user->fullname;
                        $customerEmail = $community->user->email_address;
                        $cardNumber = $default_card->card_number;
                        $cardCVC = '';
                        $cardExpMonth = $default_card->expiry_month;
                        $cardExpYear = $default_card->expiry_year;
                        $customer_id = $default_card->customer_id;
                        $itemName = $planDetails->plan_name;
                        $itemNumber = $planDetails->plan_id;
                        $payment_for = 'space_limit';
                        $transaction_payment_type = 'community_space_limit';
                        $plan_id = $planDetails->plan_id;

                        $paymenyResponse = $payDetails->jsonSerialize();
                        if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {
                            $amountPaid = $paymenyResponse['amount'];
                            $amountPaid = $amountPaid / 100;
                            $balanceTransaction = $paymenyResponse['balance_transaction'];
                            $paidCurrency = $paymenyResponse['currency'];
                            $paymentStatus = $paymenyResponse['status'];
                            $paymentDate = date('Y-m-d H:i:s');
                            $itemPrice = $amountPaid;
                            $amountPaidNew = $amountPaid;

                            $message = 'Payment successfully done for '.$number_of_users_in_plan.' MB space, your transaction id - '.$balanceTransaction;

                            $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit($community, $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_id);

                            $purchased_space_in_mb = $community->purchased_space_in_mb;
                            $community->purchased_space_in_mb = $number_of_users_in_plan + $purchased_space_in_mb;
                            $community->save();

                            if ($payment) {
                                $val = [
                                    'currency' => $paidCurrency,
                                    'invoice_total_amount_price' => $amountPaidNew,
                                    'item_quantity' => $number_of_users_in_plan,
                                    'item_name' => 'purchase_extra_space_cost',
                                    'item_description' => $paying_for_months,
                                    'item_subtotal' => $amountPaidNew,
                                    'transaction_id' => $balanceTransaction,
                                    'item_price' => $amount_for_month,
                                ];

                                $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);

                                if ($invoice) {
                                    $payment->invoice_id = $invoice->id;
                                    $payment->save();

                                    $invoice->payment_id = $payment->id;
                                    $invoice->save();
                                }
                            }

                            app('App\\Repositories\\UserRepository')->sendPaymentAlertEmail('Community increase corporate user limit', $amountPaidNew, $balanceTransaction, $community->user->fullname, $community->user->email_address, $community->user->present()->url());
                        }
                    }
                } elseif ($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');
                    $address_unit = $request->get('address_unit');
                    $cardNumber = $request->get('cardNumber');
                    $cardCVC = $request->get('cardCVC');
                    $cardExpMonth = $request->get('cardExpMonth');
                    $cardExpYear = $request->get('cardExpYear');

                    $itemName = $planDetails->plan_name;
                    $itemNumber = $planDetails->plan_id;
                    $payment_for = 'space_limit';
                    $transaction_payment_type = 'community_space_limit';
                    $plan_id = $planDetails->plan_id;

                    $source_token = $stripeToken;

                    $customer = \Stripe\Customer::create([
                        'name' => $customerName,
                        'description' => 'Space subscription',
                        'email' => $customerEmail,
                        'source' => $source_token, // This is for test
                        'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
                    ]);

                    $cardMessage = '';

                    try {
                        $payDetails = \Stripe\Charge::create([
                            'customer' => $customer->id,
                            'amount' => $payingAmount,
                            'currency' => $currency_code,
                            'description' => $itemName,
                            'metadata' => [
                                'order_id' => $orderId,
                            ],
                        ]);
                    } catch (\Stripe\Error\Base $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\Card $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\Authentication $e) {
                        $cardMessage = $e->getMessage();
                    } catch (\Stripe\Error\InvalidRequest $e) {
                        $cardMessage = $e->getMessage();
                    } catch (Exception $e) {
                        $cardMessage = $e->getMessage();
                    }

                    if ($cardMessage) {
                        \Session::flash('pay_error_msg', $cardMessage);

                        return redirect($this->community->present()->url('spacepurchase'));
                    }

                    $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'];
                        $amountPaid = $amountPaid / 100;
                        $balanceTransaction = $paymenyResponse['balance_transaction'];
                        $paidCurrency = $paymenyResponse['currency'];
                        $paymentStatus = $paymenyResponse['status'];
                        $paymentDate = date('Y-m-d H:i:s');
                        $itemPrice = $amountPaid;
                        $amountPaidNew = $amountPaid;

                        $message = 'Payment successfully done for '.$number_of_users_in_plan.' MB space, your transaction id - '.$balanceTransaction;

                        $payment = $this->communityPricingPlanPaymentRepository()->addPaymentCommunityLimit($community, $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_id, 'community', 'yes');

                        $purchased_space_in_mb = $community->purchased_space_in_mb;
                        $community->purchased_space_in_mb = $number_of_users_in_plan + $purchased_space_in_mb;
                        $community->save();

                        if ($payment) {
                            $val = [
                                'currency' => $paidCurrency,
                                'invoice_total_amount_price' => $amountPaidNew,
                                'item_quantity' => $number_of_users_in_plan,
                                'item_name' => 'purchase_extra_space_cost',
                                'item_description' => $paying_for_months,
                                'item_subtotal' => $amountPaidNew,
                                'transaction_id' => $balanceTransaction,
                                'item_price' => $amount_for_month,
                            ];

                            $invoice = $this->communityInvoiceRepository()->addCommunityAutoInvoice($val, $community);

                            if ($invoice) {
                                $payment->invoice_id = $invoice->id;
                                $payment->save();

                                $invoice->payment_id = $payment->id;
                                $invoice->save();
                            }
                        }

                        app('App\\Repositories\\UserRepository')->sendPaymentAlertEmail('Community space purchase', $amountPaidNew, $balanceTransaction, $community->user->fullname, $community->user->email_address, $community->user->present()->url());
                    } else {
                        $message = 'Payment failed.';
                    }
                }
            }
        }

        \Session::flash('message', $message);

        return redirect($this->community->present()->url('spacepurchase'));
    }

    public function listExperienceCategory()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }

        if ($this->community->enable_share_experience == 1) {
            $this->theme->share('settingPage', 'manageexperience');

            $categories = $this->experienceCategoriesRepository()->getActiveAll($this->community->id);

            return $this->render('community.pannel.experience.category-list', [
                'community' => $this->community,
                'categories' => $categories,
            ], [
                'title' => $this->setTitle(''),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function addExperienceCategory(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        if ($this->community->enable_share_experience == 1) {
            if ($val = $request->get('val')) {
                $category = $this->experienceCategoriesRepository()->add($val, $this->community);
                if ($category) {
                    \Session::flash('message', 'Category added successfully');

                    return redirect($this->community->present()->url('experience/catlist'));
                } else {
                    \Session::flash('message', 'Category name already exist');

                    return redirect($this->community->present()->url('experience/addcat'));
                }
            }

            $this->theme->share('settingPage', 'manageexperience');

            return $this->render('community.pannel.experience.category-add', [
                'community' => $this->community,
            ], [
                'title' => $this->setTitle(''),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function deleteExperienceCategory($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        if ($this->community->enable_share_experience == 1) {
            $category = $this->experienceCategoriesRepository()->getById($this->community->id, $id);
            if ($category) {
                $category->status = 0;
                $category->save();
                \Session::flash('message', 'Category deleted successfully');
            } else {
                \Session::flash('message', 'Invalid category');
            }

            return redirect($this->community->present()->url('experience/catlist'));
        }

        return redirect($this->community->present()->url());
    }

    public function deactivateExperienceCategory($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        if ($this->community->enable_share_experience == 1) {
            $category = $this->experienceCategoriesRepository()->getById(0, $id);
            if ($category) {
                $newcateory = $this->experienceCategoriesRepository()->model->newInstance();

                $newcateory->deactivated_community_id = $this->community->id;
                $newcateory->deactivated_category_id = $id;
                $newcateory->is_deactivated = 1;
                $newcateory->save();
                \Session::flash('message', 'Category deactivated successfully');
            } else {
                \Session::flash('message', 'Invalid category');
            }

            return redirect($this->community->present()->url('experience/catlist'));
        }

        return redirect($this->community->present()->url());
    }

    public function activateExperienceCategory($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        if ($this->community->enable_share_experience == 1) {
            $category = $this->experienceCategoriesRepository()->isExpCategoryDeactivated($this->community->id, $id);
            if ($category) {
                $category->delete();
                \Session::flash('message', 'Category activated successfully');
            } else {
                \Session::flash('message', 'Invalid category');
            }

            return redirect($this->community->present()->url('experience/catlist'));
        }

        return redirect($this->community->present()->url());
    }

    public function editExperienceCategory($slug, $id,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        if ($this->community->enable_share_experience == 1) {
            $category = $this->experienceCategoriesRepository()->getById($this->community->id, $id);

            if ($val = $request->get('val')) {
                $category_edited = $this->experienceCategoriesRepository()->edit($val, $this->community, $category);
                if ($category_edited) {
                    \Session::flash('message', 'Category edited successfully');

                    return redirect($this->community->present()->url('experience/catlist'));
                } else {
                    \Session::flash('message', 'Category name already exist');

                    return redirect($this->community->present()->url('experience/editcat').'/'.$category->id);
                }
            }

            $this->theme->share('settingPage', 'manageexperience');

            return $this->render('community.pannel.experience.category-edit', [
                'community' => $this->community,
                'category' => $category,
            ], [
                'title' => $this->setTitle(''),
            ]);
        }

        return redirect($this->community->present()->url());
    }

    public function aiDefaultQuestions()
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $parent_question_id = 0;
        $questions_informal = $this->aiDefaultQuestionsRepository()->getMainQuestionsInformal($community->id);
        $questions_formal = $this->aiDefaultQuestionsRepository()->getMainQuestionsFormal($community->id);
        $questions_buttons_informal = $this->aiDefaultQuestionsRepository()->getMainQuestionsButtonsInformal($community->id);
        $questions_buttons_formal = $this->aiDefaultQuestionsRepository()->getMainQuestionsButtonsFormal($community->id);

        return $this->render('community.pannel.cms.ai-questions.index-main', ['community' => $community, 'questions_informal' => $questions_informal, 'questions_formal' => $questions_formal, 'questions_buttons_informal' => $questions_buttons_informal, 'questions_buttons_formal' => $questions_buttons_formal, 'parent_question_id' => $parent_question_id], [
            'title' => $this->setTitle(trans('cms.ai-default-messages')),
        ]);
    }

    public function aiAddQuestion(Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $parent_question_id = 0;
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->addQuestion($val, $community->id);
            if ($addQuest and $addQuest->action_btn_type == 0 and $addQuest->is_action_btn == 1) {
                return redirect($this->community->present()->url('aiquestion/add/').$addQuest->id)->with('success', trans('cms.ai-question-added-successfully'));
            } else {
                return redirect($this->community->present()->url('aidefaultquestions'))->with('success', trans('cms.ai-question-added-successfully'));
            }
        }

        return $this->render('community.pannel.cms.ai-questions.add', ['parent_question_id' => $parent_question_id], [
            'title' => $this->setTitle(trans('cms.ai-add-question')),
        ]);
    }

    public function aiEditQuestion($slug, $id,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, $community->id);
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->editQuestion($question, $val, $community->id);
            if ($addQuest and $addQuest->parent_id) {
                return redirect($this->community->present()->url('aisubquestions/').$addQuest->parent_id)->with('success', trans('cms.ai-sub-question-edited-successfully'));
            } else {
                return redirect($this->community->present()->url('aidefaultquestions'))->with('success', trans('cms.ai-question-edited-successfully'));
            }
        }

        return $this->render('community.pannel.cms.ai-questions.edit', ['question' => $question], [
            'title' => $this->setTitle(trans('cms.ai-edit-question')),
        ]);
    }

    public function aiDeleteQuestion($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, $community->id);
        $parent_id = $question->parent_id;
        $question->delete();
        if ($parent_id) {
            return redirect($this->community->present()->url('aisubquestions/').$parent_id)->with('success', trans('cms.ai-question-deleted-successfully'));
        } else {
            return redirect($this->community->present()->url('aidefaultquestions'))->with('success', trans('cms.ai-question-deleted-successfully'));
        }
    }

    public function aiDeactivateQuestion($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, $community->id);
        $question->status = 0;
        $question->save();

        $parent_id = $question->parent_id;
        if ($parent_id) {
            return redirect($this->community->present()->url('aisubquestions/').$parent_id)->with('success', trans('cms.ai-question-deactivated-successfully'));
        } else {
            return redirect($this->community->present()->url('aidefaultquestions'))->with('success', trans('cms.ai-question-deactivated-successfully'));
        }
    }

    public function aiActivateQuestion($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, $community->id);
        $question->status = 1;
        $question->save();

        $parent_id = $question->parent_id;
        if ($parent_id) {
            return redirect($this->community->present()->url('aisubquestions/').$parent_id)->with('success', trans('cms.ai-question-activated-successfully'));
        } else {
            return redirect($this->community->present()->url('aidefaultquestions'))->with('success', trans('cms.ai-question-activated-successfully'));
        }
    }

    public function aiSubQuestions($slug, $parent_question_id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $questions = $this->aiDefaultQuestionsRepository()->getSubQuestions($community->id, $parent_question_id);
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($parent_question_id, $community->id);

        return $this->render('community.pannel.cms.ai-questions.index', ['questions' => $questions, 'parent_question_id' => $parent_question_id, 'question' => $question], [
            'title' => $this->setTitle(trans('cms.ai-sub-questions')),
        ]);
    }

    public function aiAddSubQuestion($slug, $parent_question_id,Request $request)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $question = $this->aiDefaultQuestionsRepository()->getByCmId($parent_question_id, $community->id);
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->addQuestion($val, $community->id);
            if ($addQuest and $addQuest->action_btn_type == 0 and $addQuest->is_action_btn == 1) {
                return redirect($this->community->present()->url('aiquestion/add/').$addQuest->id)->with('success', trans('cms.ai-question-added-successfully'));
            } else {
                return redirect($this->community->present()->url('aisubquestions/').$parent_question_id)->with('success', trans('cms.ai-sub-question-added-successfully'));
            }
        }

        return $this->render('community.pannel.cms.ai-questions.add', ['parent_question_id' => $parent_question_id, 'question' => $question], [
            'title' => $this->setTitle(trans('cms.ai-add-question')),
        ]);
    }

    public function aiChatbotTracking($slug)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $report = $this->aiChatbotTrackingRepository()->getConversations($community->id);

        return $this->render('community.pannel.cms.ai-questions.tracking', ['report' => $report], [
            'title' => $this->setTitle(trans('cms.ai-chatbot-tracking')),
        ]);
    }

    public function aiChatbotTrackingDetails($slug, $id)
    {
        if (! ($this->community->present()->isAdminSubAdmin())) {
            redirect('home')->send();
        }
        $community = $this->community;

        $report = $this->aiChatbotTrackingRepository()->getConversationsBySession($community->id, $id);

        return $this->render('community.pannel.cms.ai-questions.tracking-details', ['report' => $report, 'id' => $id], [
            'title' => $this->setTitle(trans('cms.ai-chatbot-tracking')),
        ]);
    }

    public function createAward($slug,Request $request)
    {
        $community = $this->community;

        if (! $this->exists()) {
            return $this->notFound();
        }

        $message = null;
        if ($val = $request->get('val')) {
            $form = $this->communityFormsRepository()->addAwardForm($val, $this->community->id);
            if ($form) {
                // return redirect($this->community->present()->url('awardcategrysetup/'.$form->id));
                $this->communityFormsCategoryRepository()->addDefaultCategory($this->community->id, $form->id);

                return redirect($this->community->present()->url('longforms'));
            }
        }

        return $this->render('community.pannel.cms.longforms.award.create-award', [

        ], ['title' => $this->setTitle(trans('formsurveys.create-award'))]);
    }

    public function createAwardCategory($slug, $id,Request $request)
    {
        $community = $this->community;

        if (! $this->exists()) {
            return $this->notFound();
        }

        $user = \Auth::user();

        $form = $this->communityFormsRepository()->getById($id);

        if ($form and ($form->user_id == $user->id || $this->community->present()->isAdminSubAdmin())) {

            $message = null;
            if ($val = $request->get('val')) {
                $this->communityFormsRepository()->awardCategorySetup($val, $form, $this->community->id);

                $category_title = $request->get('category_title');
                $category_description = $request->get('category_description');
                $category_heading = $request->get('category_heading');
                $category_award_sponser = $request->get('category_award_sponser');
                $category_sponsor_url = $request->get('category_sponsor_url');
                $category_sponsor_logo = $request->get('category_sponsor_logo');
                $category_ids = $request->get('category_ids');

                // return $logoimage = $request->file('category_sponsor_logo')[2];

                $this->communityFormsCategoryRepository()->addAwardCategories($form, $this->community->id, $category_title, $category_description, $category_heading, $category_award_sponser, $category_sponsor_url, $category_sponsor_logo, $category_ids);

                return redirect($this->community->present()->url('awardvotingsetup/'.$form->id));
            }

            $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($form->id);

            return $this->render('community.pannel.cms.longforms.award.award-categories', [
                'form' => $form,
                'categories' => $categories,
            ], ['title' => $this->setTitle(trans('formsurveys.create-award'))]);
        }

        return redirect($this->community->present()->url());
    }

    public function createAwardVoting($slug, $id,Request $request)
    {
        $community = $this->community;

        if (! $this->exists()) {
            return $this->notFound();
        }

        $user = \Auth::user();

        $form = $this->communityFormsRepository()->getById($id);

        if ($form and ($form->user_id == $user->id || $this->community->present()->isAdminSubAdmin())) {

            $message = null;
            if ($val = $request->get('val')) {
                $form = $this->communityFormsRepository()->awardVotingSetup($val, $form, $this->community->id);

                return redirect($this->community->present()->url('longforms'));
            }

            return $this->render('community.pannel.cms.longforms.award.award-voting', [
                'form' => $form,
            ], ['title' => $this->setTitle(trans('formsurveys.create-award'))]);
        }

        return redirect($this->community->present()->url());
    }
}

