<?php

namespace App\Http\Controllers\Admincp;

use App\Http\Controllers\Traits\LazyLoadsRepositories;
use Illuminate\Mail\Mailer;
use Illuminate\Http\Request;

class CommunityController extends AdmincpController
{
    use LazyLoadsRepositories;

    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
        parent::__construct();
        $this->activePage('communities');
    }

    public function index(Request $request)
    {

        return $this->theme->view('communities.index', [
            'communities' => $this->communityRepository()->getAllCommunitiesList($request->get('term'), $request->get('withdomain')),
        ])->render();
    }

    public function edit(Request $request,$id)
    {
        $community = $this->communityRepository()->get($id);
        $message = null;

        if ($val = $request->get('val')) {
            $this->communityRepository()->adminSave($val, $community);
            $message = 'Successfully saved';
        }

        return $this->theme->view('communities.edit', [
            'community' => $community,
            'message' => $message,
        ])->render();
    }

    public function menuSettings(Request $request, $id)
    {
        $community = $this->communityRepository()->get($id);
        $message = null;

        if ($val = $request->get('val')) {
            $this->communityMenuSettingsRepository()->saveSettings($community, $val);
            $message = 'Settings saved successfully';
        }

        $settings = $this->communityMenuSettingsRepository()->getByCommunityId($id);

        return $this->theme->view('communities.community-menu-settings', [
            'community' => $community,
            'message' => $message,
            'settings' => $settings,
        ])->render();
    }

    public function externalCommunities(Request $request)
    {
        // $languages=$this->languageRepository()->getActiveall();

        $languages = $this->languageRepository()->all();

        $this->activePage('external-communities');

        return $this->theme->view('communities.external-communities', [
            //'communities' => $this->communityRepository()->externalCommunities($request->get('access_type')),
			'communities' => $this->communityRepository()->getAllCommunitiesList($request->get('term'), $request->get('withdomain')),
            'languages' => $languages,
        ])->render();
    }

    public function communityAction(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');
        $userId = $request->get('userId');

        $this->communityRepository()->externalCommunityAction($value, $communityId, $userId);

        $this->userRepository()->externalCommunityUserAction($value, $communityId, $userId);
    }

    public function communitySignonAction(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');
        $this->communityRepository()->communitySignonAction($value, $communityId);
    }

    public function communityBusinessAction(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->communityBusinessAction($value, $communityId);
    }

    public function communityLocalAction(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->communityLocalAction($value, $communityId);
    }

    public function communityAllowBusiness(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->communityAllowBusiness($value, $communityId);
    }

    public function showCrowdfunding(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->showCrowdfunding($value, $communityId);
    }

    public function saveCommunityDomain(Request $request)
    {
        $domain = $request->get('domain');
        $communityId = $request->get('id');

        $this->communityRepository()->saveCommunityDomain($domain, $communityId);
    }

    public function surveyNominationAction(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->surveyNominationAction($value, $communityId);
    }

    public function activateCampaign(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateCampaign($value, $communityId);
    }

    public function activateEvent(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateEvent($value, $communityId);
    }

    public function activateDonation(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateDonation($value, $communityId);
    }

    public function activateZoom(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateZoom($value, $communityId);
    }

    public function activateVideoCall(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateVideoCall($value, $communityId);
    }

    public function activateActivationCode(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateActivationCode($value, $communityId);
    }

    public function activateSocialProfile(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateSocialProfile($value, $communityId);
    }

    public function activateFitness(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateFitness($value, $communityId);
    }

    public function communitySetLanguage(Request $request)
    {
        $language = $request->get('type');
        $communityId = $request->get('community_id');
        $value = $request->get('value');

        return $this->communityLanguagesRepository()->communitySetLanguage($language, $communityId, $value);
    }

    public function activateBusinessApplication(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        $this->communityRepository()->activateBusinessApplication($value, $communityId);
    }

    public function activateCrmApplication(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->activateCrmApplication($value, $communityId);
    }

    public function activateWebsiteBookmark(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->activateWebsiteBookmark($value, $communityId);
    }

    public function activateIdhubsApplication(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->activateIdhubsApplication($value, $communityId);
    }

    public function activateIdmartApplication(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->activateIdmartApplication($value, $communityId);
    }

    public function activateAIchat(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->activateAIchat($value, $communityId);
    }

    public function crmPayments()
    {
        $cmIds = $this->crmPaymentsRepository()->getPaymentCommunityIds();
        $communities = $this->communityRepository()->crmPaymentCommunities($cmIds);
        $payments = app('App\\Repositories\\CrmPaymentsRepository')->crmToTalPaymentReceived();
        $due = app('App\\Repositories\\CrmInvoicesRepository')->crmToTalPaymentDue(['type' => 'sum', 'status' => 'due']);

        return $this->theme->view('communities.crm.index', [
            'communities' => $communities,
            'payments' => $payments,
            'due' => $due,
        ])->render();
    }

    public function crmDashboard()
    {
        $cmIds = $this->crmPaymentsRepository()->getPaymentCommunityIds();
        $communities = $this->communityRepository()->crmPaymentCommunities($cmIds);

        $payments = app('App\\Repositories\\CrmPaymentsRepository')->crmToTalPaymentReceived();
        $due = app('App\\Repositories\\CrmInvoicesRepository')->crmToTalPaymentDue(['type' => 'sum', 'status' => 'due']);
        $cashout = app('App\\Repositories\\CrmPaymentsCashoutRepository')->crmToTalPaymentCashout();

        return $this->theme->view('communities.crm.dashboard', [
            'communities' => $communities,
            'payments' => $payments,
            'due' => $due,
            'cashout' => $cashout,
        ])->render();
    }

    public function addCashout(Request $request)
    {
        $val = $request->get('val');
        $this->crmPaymentsCashoutRepository()->addCashoutPayment($val);

        return redirect('/admincp/crmpayments');
    }

    public function viewCashout($id)
    {
        $transactions = $this->crmPaymentsCashoutRepository()->getCashoutPayment($id);
        $community = $this->communityRepository()->getById($id);

        return $this->theme->view('communities.crm.cashout', [
            'transactions' => $transactions,
            'community' => $community,
        ])->render();
    }

    public function getCashout(Request $request)
    {
        $id = $request->get('typeid');
        $transaction = $this->crmPaymentsCashoutRepository()->getById($id);

        return json_encode([
            'cashout_date' => $transaction->cashout_date,
            'amount' => $transaction->amount,
            'transaction_id' => $transaction->transaction_id,
            'note' => $transaction->note,
        ]);
    }

    public function plans()
    {
        $this->activePage('plans');
        $plans = $this->pricingPlansRepository()->getPlans();

        return $this->theme->view('plans.plan-list', [
            'plans' => $plans,

        ])->render();
    }

    public function planFeatures()
    {
        $this->activePage('plans');
        $features = '';

        return $this->theme->view('plans.feature-list', [
            'features' => $features,
        ])->render();
    }

    public function featuresList()
    {
        $this->activePage('plans');
        $features = $this->pricingFeaturesRepository()->getFeatures();

        return $this->theme->view('plans.feature-list', [
            'features' => $features,
        ])->render();
    }

    public function savePlanFeature(Request $request)
    {
        $id = $request->get('id');
        $plan = $request->get('plan');
        $value = $request->get('value');

        return $this->pricingFeaturesRepository()->savePlanFeatures($id, $plan, $value);
    }

    public function overridePlanFeature(Request $request)
    {
        $id = $request->get('id');
        $type = $request->get('type');
        $value = $request->get('value');

        $community = $this->communityRepository()->getById($id);

        if ($community) {
            if ($type == 'allow_user_create_business_override') {
                $community->allow_user_create_business_override = $value;
            } elseif ($type == 'show_crowdfunding_override') {
                $community->show_crowdfunding_override = $value;
            } elseif ($type == 'survey_nomination_action_override') {
                $community->survey_nomination_action_override = $value;
            } elseif ($type == 'activate_campaign_override') {
                $community->activate_campaign_override = $value;
            } elseif ($type == 'event_access_override') {
                $community->event_access_override = $value;
            } elseif ($type == 'donation_access_override') {
                $community->donation_access_override = $value;
            } elseif ($type == 'videocall_access_override') {
                $community->videocall_access_override = $value;
            } elseif ($type == 'show_activationcode_page_override') {
                $community->show_activationcode_page_override = $value;
            } elseif ($type == 'show_socialprofile_override') {
                $community->show_socialprofile_override = $value;
            } elseif ($type == 'fitness_access_override') {
                $community->fitness_access_override = $value;
            } elseif ($type == 'join_business_access_override') {
                $community->join_business_access_override = $value;
            } elseif ($type == 'crm_access_override') {
                $community->crm_access_override = $value;
            } elseif ($type == 'idhubs_access_override') {
                $community->idhubs_access_override = $value;
            } elseif ($type == 'idmart_access_override') {
                $community->idmart_access_override = $value;
            } elseif ($type == 'ai_chat_access_override') {
                $community->ai_chat_access_override = $value;
            }

            $community->save();
        }
    }

    public function crmUserRegister()
    {
        $communities = $this->communityRepository()->externalCommunities();
        foreach ($communities as $community) {
            if ($community->user) {
                $this->communityRepository()->registerCrmUser($community->id);
            }
        }

        return 'executed';
    }

    public function editPlan($id, Request $request)
    {
        $plan = $this->pricingPlansRepository()->getPlanById($id);

        if ($val = $request->get('val')) {
            $plan_name = $val['plan_name'];
            $plan_description = $val['plan_description'];
            $price_monthly = $val['price_monthly'];
            $price_yearly = $val['price_yearly'];
            $trial_days = $val['trial_days'];
            $save_percent_texts = $val['save_percent_texts'];
            //$default_plan = $val['default_plan'];
			$default_plan = 0;
            $user_limit = $val['user_limit'];
            $is_plan_free = $val['is_plan_free'];
            //$can_add_extra_user = $val['can_add_extra_user'];
            //$monthly_price_per_extra_user = $val['monthly_price_per_extra_user'];
			$community_user_limit= $val['community_user_limit'];
			$space_for_corporate= $val['space_for_corporate'];
			$space_for_community_users= $val['space_for_community_users'];
			$emails= $val['emails'];
			
			$plan_type= $val['plan_type'];
			
            if ($is_plan_free == 1) {
                $price_monthly = 0;
                $price_yearly = 0;
                $trial_days = 0;
                $save_percent_texts = '';
            }

            $plan->plan_name = $plan_name;
            $plan->plan_description = $plan_description;
            $plan->price_monthly = $price_monthly;
            $plan->price_yearly = $price_yearly;
            $plan->trial_days = $trial_days;
            $plan->save_percent_texts = $save_percent_texts;
            $plan->default_plan = $default_plan;
            $plan->user_limit = $user_limit;
            $plan->is_plan_free = $is_plan_free;
            //$plan->can_add_extra_user = $can_add_extra_user;
            //$plan->monthly_price_per_extra_user = $monthly_price_per_extra_user;
			
			$plan->community_user_limit = $community_user_limit;
			$plan->space_for_corporate = $space_for_corporate;
			$plan->space_for_community_users = $space_for_community_users;
			
			$plan->plan_type = $plan_type;			
			$plan->emails = $emails;
			
            $plan->save();

            if ($default_plan == 1) {
                $this->pricingPlansRepository()->unsetOtherPlan($id);
            }

            return redirect('/admincp/admincp-plans');
        }

        return $this->theme->view('plans.edit-plan', [
            'plan' => $plan,
        ])->render();
    }

    public function addPlan(Request $request)
    {
        $this->activePage('plans');

        if ($val = $request->get('val')) {
            $plan = $this->pricingPlansRepository()->createPlan($val);

            \Session::flash('success', 'Plan created successfully.');
            return redirect('/admincp/admincp-plans');
        }

        return $this->theme->view('plans.add-plan', [
        ])->render();
    }
	
	public function setPlanFeature($id, Request $request)
    {
		$plan = $this->pricingPlansRepository()->getPlanById($id);
        if (! $plan) {
            \Session::flash('success', 'Plan not found.');
            return redirect('/admincp/admincp-plans');
        }

		$features = $this->pricingPlansFeaturesRepository()->getAllActive();
        $selectedFeatureIds = $this->plansFeaturesSelectedRepository()->getSelectedFeatureIdsForPlan($id);

        return $this->theme->view('plans.set-plan-features', [
            'plan' => $plan,
            'features' => $features,
            'selectedFeatureIds' => $selectedFeatureIds,
        ])->render();
	}

    public function saveSelectedPlanFeatures($id, Request $request)
    {
        $plan = $this->pricingPlansRepository()->getPlanById($id);
        if (! $plan) {
            \Session::flash('success', 'Plan not found.');
            return redirect('/admincp/admincp-plans');
        }

        $featureIds = $request->get('feature_ids', []);
        if (! is_array($featureIds)) {
            $featureIds = [];
        }

        $this->plansFeaturesSelectedRepository()->syncSelectedFeaturesForPlan($id, $featureIds);
        \Session::flash('success', 'Features selected successfully.');

        return redirect()->route('admincp-plan-set-features', ['id' => $id]);
    }

    public function pricingPlansFeaturesList()
    {
        $this->activePage('plans');
		$features = $this->pricingPlansFeaturesRepository()->getAllActive();

        return $this->theme->view('plans.pricing-plans-features-list', [
            'features' => $features,
        ])->render();
    }

    public function pricingPlansFeatureEdit($id, Request $request)
    {
        $this->activePage('plans');
        $feature = $this->pricingPlansFeaturesRepository()->getById($id);
        if (! $feature) {
            \Session::flash('success', 'Feature not found.');
            return redirect()->route('admincp-pricing-plans-features-list');
        }

        $message = null;
        if ($val = $request->get('val')) {
            $this->pricingPlansFeaturesRepository()->edit($val, $feature);
            $message = 'Saved successfully';
        }

        return $this->theme->view('plans.pricing-plans-features-edit', [
            'feature' => $feature,
            'message' => $message,
        ])->render();
    }

    public function allowGlobalAccess(Request $request)
    {
        $value = $request->get('value');
        $communityId = $request->get('communityId');

        return $this->communityRepository()->allowGlobalAccess($value, $communityId);
    }

    public function communityGiftPayments()
    {
        $communities = $this->communityRepository()->getGiftCommunitites();

        return $this->theme->view('communities.gifts.payments', ['communities' => $communities])->render();
    }

    public function communityGiftPaymentSend($id, Request $request)
    {
        $community = $this->communityRepository()->getById($id);

        if ($val = $request->get('val')) {
            $gift_payment_send = $this->giftsCashoutRepository()->addGiftPaymentSend($community, $val);
            \Session::flash('success', 'Record saved successfully.');

            return redirect('/admincp/community-gift-payments');
        }

        return $this->theme->view('communities.gifts.send-payment', ['community' => $community])->render();
    }

    public function communityGiftPaymentDetails($id)
    {
        $community = $this->communityRepository()->getById($id);
        $details = $this->giftsCashoutRepository()->getComunityOwnCashout($community->id);

        return $this->theme->view('communities.gifts.payment-report', ['community' => $community, 'details' => $details])->render();
    }

    public function communityPaymentsDashboard(Request $request)
    {
        $this->activePage('Community Cards');

        $selected_year = $request->get('selected_year');
        $term = $request->get('term');
        $card_loaded = $request->get('card_loaded');

        if (! $selected_year) {
            $selected_year = date('Y');
        }

        $communities = $this->communityRepository()->getAllActiveCommunitites($term, $card_loaded);

        // $cards=$this->communityPricingPlanPaymentCardsRepository()->getCommunityCardDetails();

        return $this->theme->view('communities.payment-dashboard', [
            'communities' => $communities,
            'selected_year' => $selected_year,
            'card_loaded' => $card_loaded,
        ])->render();
    }

    public function cardAlertEmail(Request $request)
    {
        $id = $request->get('id');
        $type = $request->get('type');
        $community = $this->communityRepository()->getById($id);
        if ($community) {
            if ($type == 'updatecard') {
                return (string) $this->theme->section('communities.send-card-alert', ['community' => $community])->render();
            } else {
                return (string) $this->theme->section('communities.send-card-alert-global', ['community' => $community])->render();
            }
        } else {
            return 'Invalid community';
        }
    }

    public function cardCustomAlertEmail(Request $request)
    {
        $id = $request->get('id');
        $subject = $request->get('subject');
        $body = $request->get('body');

        $community = $this->communityRepository()->getById($id);
        if ($community) {
            $this->communityRepository()->sendCardCustomAlert($community, $subject, $body);

            return 'Email send successfully';
        } else {
            return 'Invalid community';
        }
    }

    public function sendCardAlert(Request $request)
    {
        $id = $request->get('id');
        $community = $this->communityRepository()->getById($id);
        if ($community) {
            $this->communityRepository()->sendCardExpiryAlert($community);

            return 'Email send successfully';
        } else {
            return 'Invalid community';
        }
    }

    public function sendCardAlertGlobal(Request $request)
    {
        $id = $request->get('id');
        $community = $this->communityRepository()->getById($id);
        if ($community) {
            $this->communityRepository()->sendCardExpiryAlertGlobal($community);

            return 'Email send successfully';
        } else {
            return 'Invalid community';
        }
    }

    public function setPlanAccess(Request $request)
    {
        $id = $request->get('id');
        $pid = $request->get('pid');
        $value = $request->get('value');

        $community = $this->communityRepository()->getById($id);
        if ($community) {
            if ($pid == 1) {
                $community->pricing_plan_1_access = $value;
                $community->save();
            } elseif ($pid == 2) {
                $community->pricing_plan_2_access = $value;
                $community->save();
            } elseif ($pid == 3) {
                $community->pricing_plan_3_access = $value;
                $community->save();
            } elseif ($pid == 4) {
                $community->special_plan_access = $value;
                $community->save();
            }
        } else {
            return 'Invalid community';
        }
    }

    public function statistics(Request $request)
    {
        $community_id = $request->get('community_id');
        // $community_id=33;
        $community = '';

        $date = new \DateTime('7 days ago');
        $date->format('Y-m-d');

        $currentDate = date('Y-m-d');
        $dates = [];
        $givenValue = 0; // number of x value
        for ($i = -7; $i <= $givenValue; $i++) {
            array_push($dates, date('Y/m/d', strtotime($i.'days', strtotime($currentDate))));
        }

        $visitorsData = [];
        $pageViewData = [];

        $chartType = $request->get('charttype');

        if (! $chartType) {
            $chartType = 'bar';
        }

        if ($chartType == 'area') {
            foreach ($dates as $dt) {
                $visitingDate = date('Y-m-d', strtotime($dt));

                $visitorsData[] = [
                    'date' => $dt,
                    'value' => $this->siteVisitorsDataRepository()->getCountAll($community_id, 'firstvisit', $visitingDate),
                ];

                $pageViewData[] = [
                    'date' => $dt,
                    'value' => $this->siteVisitorsDataRepository()->getCountAll($community_id, 'pageviews', $visitingDate),
                ];
            }
        } else {
            foreach ($dates as $dt) {
                $visitingDate = date('Y-m-d', strtotime($dt));
                $visitorsData[] = [
                    'group_name' => 'Visitors',
                    'name' => date('j M Y', strtotime($dt)),
                    'value' => $this->siteVisitorsDataRepository()->getCountAll($community_id, 'firstvisit', $visitingDate),
                ];
            }

            foreach ($dates as $dt) {
                $visitingDate = date('Y-m-d', strtotime($dt));
                $visitorsData[] = [
                    'group_name' => 'PageViews',
                    'name' => date('j M Y', strtotime($dt)),
                    'value' => $this->siteVisitorsDataRepository()->getCountAll($community_id, 'pageviews', $visitingDate),
                ];
            }
        }

        $pageViews = $this->siteVisitorsDataRepository()->pageViewsAll($community_id);
        $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'unique_visitors', 'unique_visitors');
        $pageViewCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'totalpageviews', 'totalpageviews');
        $visitDates = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'visitingdates', 'visitingdates');

        // return $visitorsData;

        return $this->render('visitors.index', [
            'community' => $community,
            'pageViews' => $pageViews,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'pageViewCount' => $pageViewCount,
            'visitorsData' => json_encode($visitorsData),
            'pageViewData' => json_encode($pageViewData),
            'visitDates' => $visitDates,
            'chartType' => $chartType,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsGeographic(Request $request)
    {
        $community_id = $request->get('community_id');
        $community = '';

        $geographic = $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'allcountries', 'allcountries');

        $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'unique_visitors', 'unique_visitors');

        $geographicCountries = $this->siteVisitorsDataRepository()->geographicCountriesAll($community_id);

        $geographicCountriesNames = $this->siteVisitorsDataRepository()->geographicCountriesNamesAll($community_id);

        return $this->render('visitors.geographic', [
            'community' => $community,
            'geographic' => $geographic,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'geographicCountries' => $geographicCountries,
            'geographicCountriesNames' => $geographicCountriesNames,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsGeographicCities(Request $request)
    {
        $community_id = $request->get('community_id');
        $community = '';

        $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'unique_visitors', 'unique_visitors');
        $geographicCities = $this->siteVisitorsDataRepository()->geographicCitiesAll($community_id);

        return $this->render('visitors.geographic-cities', [
            'community' => $community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'geographicCities' => $geographicCities,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsPages(Request $request)
    {
        $viewdate = $request->get('viewdate');
        $community_id = $request->get('community_id');
        $community = '';

        if ($viewdate) {
            $pageViews = $this->siteVisitorsRepository()->visitorPagesDateWiseAll($community_id, $viewdate);
            $visitingDate = date('Y-m-d', strtotime($viewdate));
            $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'firstvisit', $visitingDate);
            $pageViewCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'pageviews', $visitingDate);
        } else {
            $pageViews = $this->siteVisitorsDataRepository()->pageViewsAll($community_id);
            $uniqueVisitorsCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'unique_visitors', 'unique_visitors');
            $pageViewCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'totalpageviews', 'totalpageviews');
        }

        $visitDates = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'visitingdates', 'visitingdates');

        return $this->render('visitors.pages', [
            'community' => $community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'visitDates' => $visitDates,
            'pageViewCount' => $pageViewCount,
            'pageViews' => $pageViews,
            'viewdate' => $viewdate,
            'community_id' => $community_id,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function ipPages($ip, Request $request)
    {
        $viewdate = $request->get('viewdate');
        $community_id = $request->get('community_id');
        $community = '';
        $order = $request->get('order');

        $pageViews = $this->siteVisitorsRepository()->allPagesLoadedByIp($community_id, $viewdate, $ip, $order);
        $uniqueVisitorsCount = 0;
        $pageViewCount = 0;

        return $this->render('visitors.ip-pages', [
            'community' => $community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'pageViewCount' => $pageViewCount,
            'pageViews' => $pageViews,
            'viewdate' => $viewdate,
            'community_id' => $community_id,
            'ip_address' => $ip,
            'order' => $order,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function ipListed(Request $request)
    {
        $community_id = $request->get('community_id');
        $community = '';

        $ip_listed = $this->siteVisitorsDataRepository()->getIpsData($community_id);

        return $this->render('visitors.ip-listed', [
            'community' => $community,
            'ip_listed' => $ip_listed,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsPagesLoaded(Request $request)
    {
        $viewdate = $request->get('viewdate');
        $community_id = $request->get('community_id');
        $community = '';
        $order = $request->get('order');

        $pageViews = $this->siteVisitorsRepository()->allPagesLoaded($community_id, $viewdate, $order);
        $uniqueVisitorsCount = 0;
        $pageViewCount = 0;

        return $this->render('visitors.pages-loaded', [
            'community' => $community,
            'uniqueVisitorsCount' => $uniqueVisitorsCount,
            'pageViewCount' => $pageViewCount,
            'pageViews' => $pageViews,
            'viewdate' => $viewdate,
            'community_id' => $community_id,
            'order' => $order,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsUsers(Request $request)
    {
        $viewdate = $request->get('viewdate');
        $community_id = $request->get('community_id');
        $community = '';

        if ($viewdate) {
            $visitingDate = date('Y-m-d', strtotime($viewdate));
        } else {
            $visitingDate = date('Y-m-d');
        }

        $pageViewCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'pageviews', $visitingDate);
        // $users=$this->siteVisitorsRepository()->visitorsUsersAll($community_id,$visitingDate);
        $users = $this->siteVisitorsDataRepository()->getIpUsersData($community_id, $visitingDate);

        /*return $this->render('visitors.users', [
                        'community'=>$community,
                        'users'=>$users,
                        'viewdate'=>$viewdate,
                        'pageViewCount'=>$pageViewCount,
                        'community_id'=>$community_id,
                    ], [
                        'title' => $this->setTitle(''),
        ]);*/

        return $this->render('visitors.users-data', [
            'community' => $community,
            'users' => $users,
            'viewdate' => $viewdate,
            'pageViewCount' => $pageViewCount,
            'community_id' => $community_id,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorsEngagement(Request $request)
    {
        $community_id = $request->get('community_id');
        $community = '';

        $engagementData = $this->siteVisitorsDataRepository()->engagementDataAll($community_id);

        return $this->render('visitors.engagement', [
            'community' => $community,
            'engagementData' => $engagementData,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function visitorSystem(Request $request)
    {
        $community_id = $request->get('community_id');
        $community = '';

        $pageViewCount = $this->siteVisitorsDataRepository()->getCountAll($community_id, 'totalpageviews', 'totalpageviews');
        $browserData = $this->siteVisitorsDataRepository()->browserDataAll($community_id);

        return $this->render('visitors.system', [
            'community' => $community,
            'pageViewCount' => $pageViewCount,
            'browserData' => $browserData,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function domainsCreated()
    {
        $domains = $this->resumeRepository()->getDomainCreatedList();

        return $this->render('domains.index', [
            'domains' => $domains,
        ], [
            'title' => $this->setTitle('Domain List'),
        ]);
    }

    public function domainsChangeStatus(Request $request)
    {
        $val = $request->get('val');
        $id = $request->get('id');

        $resume = $this->resumeRepository()->getById($id);
        if ($resume) {
            $resume->domain_activated = $val;
            $resume->save();
        }
    }

    public function domainsSendAlert(Request $request)
    {
        $id = $request->get('id');
        $resume = $this->resumeRepository()->getByIdWithUser($id);
        if ($resume) {
            $authUser = $resume->user;

            $domain_name = $resume->domain_name;

            $domain_url = generateResumeProfileOwnUrl($resume);

            $api_email = config('personal-custom-domain-api-email-address');
            $api_firstname = config('personal-custom-domain-api-first-name');

            try {
                $this->mailer->send('emails.domain.activated-user', [
                    'username' => $authUser->username,
                    'fullname' => $authUser->fullname,
                    'email_address' => $authUser->email_address,
                    'user_url' => $authUser->present()->url(),
                    'domain_name' => $domain_name,
                    'domain_url' => $domain_url,
                ], function ($mail) use ($authUser, $domain_name) {
                    $mail->to($authUser->email_address, $authUser->fullname)
                        ->subject('Your Domain '.$domain_name.' is Ready');
                });
            } catch (\Exception $e) {
                // return $e;
            }

            try {
                $this->mailer->send('emails.domain.activated-admin', [
                    'username' => $authUser->username,
                    'fullname' => $authUser->fullname,
                    'email_address' => $authUser->email_address,
                    'user_url' => $authUser->present()->url(),
                    'domain_name' => $domain_name,
                    'domain_url' => $domain_url,
                ], function ($mail) use ($api_email, $api_firstname, $domain_name) {
                    $mail->to($api_email, $api_firstname)
                        ->subject('Domain '.$domain_name.' is Ready');
                });
            } catch (\Exception $e) {
                // return $e;
            }

            $this->notificationRepository()->send($authUser->id, [
                'path' => 'notification.domain.activated-user',
                'type' => $domain_name,
            ], 1);

            $this->notificationRepository()->send(1, [
                'path' => 'notification.domain.activated-admin',
                'type' => $domain_name,
            ], $authUser->id);
        }
    }

    public function aiChatbotSetting(Request $request)
    {
        if ($val = $request->get('val')) {
            $addContents = $this->communityHomeContentsRepository()->aiChatbotSettingMain($val);

            return redirect('/admincp/ai-chatbot-setting')->with('success', 'Settings saved successfully');
        }

        return $this->render('configuration.chatbot-settings', [], [
            'title' => $this->setTitle('AI Chatbot Settings'),
        ]);
    }

    public function aiChatbotTracking()
    {
        $report = $this->aiChatbotTrackingRepository()->getConversations(0);

        return $this->render('ai-questions.tracking', ['report' => $report], [
            'title' => $this->setTitle('AI Chatbot Tracking'),
        ]);
    }

    public function aiChatbotTrackingDetails($id)
    {
        $report = $this->aiChatbotTrackingRepository()->getConversationsBySession(0, $id);

        return $this->render('ai-questions.tracking-details', ['report' => $report, 'id' => $id], [
            'title' => $this->setTitle('AI Chatbot Tracking'),
        ]);
    }

    public function aiDefaultQuestions()
    {
        $parent_question_id = 0;
        $questions_informal = $this->aiDefaultQuestionsRepository()->getMainQuestionsInformal(0);
        $questions_formal = $this->aiDefaultQuestionsRepository()->getMainQuestionsFormal(0);
        $questions_buttons_informal = $this->aiDefaultQuestionsRepository()->getMainQuestionsButtonsInformal(0);
        $questions_buttons_formal = $this->aiDefaultQuestionsRepository()->getMainQuestionsButtonsFormal(0);

        return $this->render('ai-questions.index-main', ['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('AI Default Questions'),
        ]);
    }

    public function aiEditFile(Request $request)
    {
        if (config('ai_chatbot_file')) {
            $file = \Image::url(config('ai_chatbot_file'));

            if ($val = $request->get('val')) {

                $file_data = $val['file_data'];

                $CDNRepository = app('App\\Repositories\\CDNRepository');

                $save_file = $CDNRepository->saveEditFile($file_data, config('ai_chatbot_file'));

                return redirect('/admincp/ai-chatbot-setting')->with('success', 'File changed successfully');
            }

            return $this->render('ai-questions.edit-file', ['file' => $file], [
                'title' => $this->setTitle('AI File Edit'),
            ]);
        }

        return redirect('/admincp/ai-chatbot-setting')->with('success', 'No file found to edit');
    }

    public function aiSubQuestions($parent_question_id)
    {
        $questions = $this->aiDefaultQuestionsRepository()->getSubQuestions(0, $parent_question_id);
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($parent_question_id, 0);

        return $this->render('ai-questions.index', ['questions' => $questions, 'parent_question_id' => $parent_question_id, 'question' => $question], [
            'title' => $this->setTitle('AI Sub Questions'),
        ]);
    }

    public function aiAddQuestion(Request $request)
    {
        $parent_question_id = 0;
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->addQuestion($val, 0);
            if ($addQuest and $addQuest->action_btn_type == 0 and $addQuest->is_action_btn == 1) {
                return redirect('/admincp/aiquestion/add/'.$addQuest->id)->with('success', 'Question added successfully');
            } else {
                return redirect('/admincp/aidefaultquestions')->with('success', 'Question added successfully');
            }
        }

        return $this->render('ai-questions.add', ['parent_question_id' => $parent_question_id], [
            'title' => $this->setTitle('AI Add Question'),
        ]);
    }

    public function aiAddSubQuestion($parent_question_id, Request $request)
    {
        // $parent_question_id=0;
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($parent_question_id, 0);
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->addQuestion($val, 0);
            if ($addQuest and $addQuest->action_btn_type == 0 and $addQuest->is_action_btn == 1) {
                return redirect('/admincp/aiquestion/add/'.$addQuest->id)->with('success', 'Question added successfully');
            } else {
                return redirect('/admincp/aisubquestions/'.$parent_question_id)->with('success', 'Sub Question added successfully');
            }
        }

        return $this->render('ai-questions.add', ['parent_question_id' => $parent_question_id, 'question' => $question], [
            'title' => $this->setTitle('AI Add Question'),
        ]);
    }

    public function aiEditQuestion($id, Request $request)
    {
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, 0);
        if ($val = $request->get('val')) {
            $addQuest = $this->aiDefaultQuestionsRepository()->editQuestion($question, $val, 0);
            if ($addQuest and $addQuest->parent_id) {
                return redirect('/admincp/aisubquestions/'.$addQuest->parent_id)->with('success', 'Sub question edited successfully');
            } else {
                return redirect('/admincp/aidefaultquestions')->with('success', 'Question edited successfully');
            }
        }

        return $this->render('ai-questions.edit', ['question' => $question], [
            'title' => $this->setTitle('AI Edit Question'),
        ]);
    }

    public function aiDeleteQuestion($id)
    {
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, 0);
        $parent_id = $question->parent_id;
        $question->delete();
        if ($parent_id) {
            return redirect('/admincp/aisubquestions/'.$parent_id)->with('success', 'Question deleted successfully');
        } else {
            return redirect('/admincp/aidefaultquestions')->with('success', 'Question deleted successfully');
        }
    }

    public function aiDeactivateQuestion($id)
    {
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, 0);
        $question->status = 0;
        $question->save();

        $parent_id = $question->parent_id;
        if ($parent_id) {
            return redirect('/admincp/aisubquestions/'.$parent_id)->with('success', 'Question deactivated successfully');
        } else {
            return redirect('/admincp/aidefaultquestions')->with('success', 'Question deactivated successfully');
        }
    }

    public function aiActivateQuestion($id)
    {
        $question = $this->aiDefaultQuestionsRepository()->getByCmId($id, 0);
        $question->status = 1;
        $question->save();

        $parent_id = $question->parent_id;
        if ($parent_id) {
            return redirect('/admincp/aisubquestions/'.$parent_id)->with('success', 'Question activated successfully');
        } else {
            return redirect('/admincp/aidefaultquestions')->with('success', 'Question activated successfully');
        }
    }

    public function listExpCategories()
    {
        $categories = $this->experienceCategoriesRepository()->getActiveAll(0);

        return $this->theme->view('experience.categories', [
            'categories' => $categories,
            'title' => 'Experience Categories List',
        ])->render();
    }

    public function categoryExpAdd(Request $request)
    {
        if ($val = $request->get('val')) {
            $category = $this->experienceCategoriesRepository()->addDefault($val);
            if ($category) {
                \Session::flash('success', 'Category added successfully');

                return \Redirect::route('admincp-exp-categories');
            } else {
                \Session::flash('success', 'Category name already exist');

                return \Redirect::route('admincp-experience-add-category');
            }
        }

        return $this->theme->view('experience.add-category', [
            'title' => 'Add Experience Category',
        ])->render();
    }

    public function categoryExpEdit($id, Request $request)
    {
        $category = $this->experienceCategoriesRepository()->getById(0, $id);

        if ($val = $request->get('val')) {

            $category_edited = $this->experienceCategoriesRepository()->editDefault($val, $category);
            if ($category_edited) {
                \Session::flash('success', 'Category edited successfully');

                return \Redirect::route('admincp-exp-categories');
            } else {
                \Session::flash('success', 'Category name already exist');

                return \Redirect::route('admincp-exp-categories');
            }
        }

        return $this->theme->view('experience.edit-category', [
            'title' => 'Edit Experience Category',
            'category' => $category,
        ])->render();
    }

    public function categoryExpDelete($id)
    {
        $category = $this->experienceCategoriesRepository()->getById(0, $id);
        if ($category) {
            $category->status = 0;
            $category->save();
            \Session::flash('success', 'Category deleted successfully');
        } else {
            \Session::flash('success', 'Invalid category');
        }

        return \Redirect::route('admincp-exp-categories');
    }
}

