<?php

namespace  App\Http\Controllers;
use App\Http\Controllers\Traits\LazyLoadsRepositories;

use App\Http\Controllers\Base\UserBaseController;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;

class UserHomeController extends UserBaseController
{
    use LazyLoadsRepositories;
    
    public function __construct(Mailer $mailer)
    {
        parent::__construct();
		$this->mailer = $mailer;
    }

    public function index(Request $request)
    {		
        if (\Auth::check()) {

            if (! isMobile()) {
                if (\Request::url() != config('app.url').'/home') {
                    
                }
            }

            $userid = \Auth::user()->id;

            $user = \Auth::user();
           
            \Auth::user()->present()->saveVisitingCommunity(0);
			
			$pg = $request->get('pg');
			
			//$myOrgCreated=\Auth::user()->present()->isMyCommunityCreated(); 
			$myOrgCreated=\Auth::user()->present()->myCommunityCreated(); 
			if($myOrgCreated || $pg=='explore'){		
				return $this->render('user.home.index', ['posted_community' => ''],
					['title' => $this->setTitle(trans('global.home'))]
				);
			}else{
				return redirect('/user/apps/categories');
			}	

            /*if($user->present()->canAccessSite())
            {
                return $this->render('user.home.index',['posted_community'=>""],
                    ['title' => $this->setTitle(trans('global.home'))]
                );
            }else{

                $url = \URL::route('edit-profile');
                return redirect($url);
            }*/
        } else {
            return redirect(config('app.url'));
            // return redirect('/');
        }
    }

    public function tagSuggestion(Request $request)
    {
        return $this->theme->section('user.tag.suggestion', ['users' => $this->userRepository()->friendsSuggest($request->get('text'), 5)]);
    }

    public function tagUsername(Request $request)
    {
        $communityId = $request->get('communityId');

        if ($communityId) {

            $community = $this->communityRepository()->getById($communityId);

            $userids = $this->communityMemberRepository()->getUserIds($communityId);

            array_push($userids, $community->user_id);

            $users = $this->userRepository()->searchByUsernameCommunity($request->get('text'), $userids, 5);
        } else {
            $users = $this->userRepository()->searchByUsername($request->get('text'), 5);
        }

        return $this->theme->section('user.tag.username', ['users' => $users]);
    }

    public function tagChattingUsername(Request $request)
    {
        $groupId = $request->get('groupId');
        $groupType = $request->get('groupType');

        // return $groupType;
        $users = '';
        if ($groupId and $groupType == 'community-group') {

            $category = $this->communityCategoryRepository()->getById($groupId);
            if ($category) {
                if ($category->group_type == 0) {
                    $userids = $this->communityCategoryMembersRepository()->getMembersIds($category->community_id, $category->id);
                } else {
                    $userids = $this->communityMemberRepository()->getUserIds($category->community_id);
                }

                //array_push($userids);
                $users = $this->userRepository()->searchByUsernameCommunity($request->get('text'), $userids, 5);
            }
        } elseif ($groupId and $groupType == 'personal-group') {
            $users_ids = $this->messageGroupMembersRepository()->getMembers($groupId);
            $users = $this->userRepository()->searchByUsernameCommunity($request->get('text'), $users_ids, 5);
        } elseif ($groupId and $groupType == 'personal-chat') {
            $users_ids = [$groupId];
            $users = $this->userRepository()->searchByUsernameCommunity($request->get('text'), $users_ids, 5);
        }

        return $this->theme->section('user.tag.chatusername', ['users' => $users]);
    }

    public function resumeUsername(Request $request)
    {
        $users = '';
        $users_ids = $this->resumeRepository()->getUserIds();
        $users = $this->userRepository()->searchByUsername($request->get('text'), 5);

        return $this->theme->section('user.tag.username', ['users' => $users]);
    }

    public function hashTag(Request $request)
    {
        return $this->theme->section('user.tag.hashtag', ['hashtags' => $this->hashtagRepository()->search($request->get('text'), 5)]);
    }

    public function suggestion($type)
    {
        // print_r($this->userRepository()->suggest(10, null, true)); die('hello');
        $content = null;
        $title = null;
        switch ($type) {
            default:
                $content = $this->theme->section('user.suggestion.people', ['users' => $this->userRepository()->suggest(10, null, true)]);
                $title = $this->setTitle(trans('user.people-you-know'));
                break;
        }

        return $this->render('user.suggestion.layout', ['content' => $content, 'title' => $title]);
    }

    public function popover($id)
    {
        $user = $this->userRepository()->findById($id);

        if (! empty($user)) {
            return $this->theme->section('user.popover', ['user' => $user]);
        }
    }

    public function getUserAvatar($id)
    {

        $user = $this->userRepository()->findById($id);
        if (! empty($user)) {
            return $user->present()->getAvatar(50);
        }

        return false;
    }

    public function getEmoticons()
    {
        $emoticons = \Theme::option()->get('emoticons');
        if ($emoticons) {
            return $emoticons;
        }

        return false;
    }

    public function dashboardContents()
    {
        $sorttype = 'cmdashboardposts';
        $communitySlug = \Request::segment(2);
        $cmntData = app('App\\Repositories\\CommunityRepository')->getBySlug($communitySlug);

                $posts = $this->postRepository()->lists('community-'.$cmntData->id, 0, null, null, null, null, $sorttype);

        return $this->render('user.home.dashboard-contents', [
            'posts' => $posts,
            'pageHeading' => 'Public Posts',
            'community' => $cmntData,
            'sorttype' => $sorttype,
        ], [
            ['title' => $this->setTitle('Dashboard Contents')],
        ]);

    }

    public function managePages(Request $request)
    {$term = $request->get('term');

        $businessIds = $this->pageAdminRepository()->getByUserId();

        $pages = $this->pageRepository()->getByIds($businessIds);

        return $this->render('page.manage-pages', [
            'pages' => $pages,
        ], [
            ['title' => $this->setTitle('Manage Pages')],
        ]);
    }

    public function associatedCommunity()
    {
        $redirectUrl = \URL::route('edit-profile');

        $isProfileCompleted = \Auth::user()->present()->checkUserProfile();

        if (\Session::has('theNewCommunityId') and \Session::get('theNewCommunityId') != '') {
            $loggedInCmId = \Session::get('theNewCommunityId');
            $loggedInCm = $this->communityRepository()->getById($loggedInCmId);
            if ($loggedInCm) {
                if ($loggedInCm->present()->canShowCompleteProfilePage() == 0 || $isProfileCompleted == 1) {
                    $profileRedirectUrl = \Auth::user()->present()->profileRedirectUrl();
                    if ($profileRedirectUrl) {
                        $redirectUrl = $profileRedirectUrl;
                    }
                }
            }
        }

        \Session::put('activationVisited', 'yes');

        return $this->render('user.organization-identity', [
            'redirectUrl' => $redirectUrl,
        ], [
            'title' => $this->setTitle('Organization Identity'),
        ]);
    }

    public function sellCourseWatch($id, $topic_id, $order_id)
    {
        $userid = \Auth::user()->id;

        $product = $this->businessProductsRepository()->getById($id);
        $orders = $this->businessProductsOrdersRepository()->getById($order_id);
        if ($orders and $orders->user_id == $userid) {
            $topic = $this->businessProductsCourseContentsTopicsRepository()->getTopicById($id, $topic_id);

            return $this->render('user.my-orders-watch-course', [
                'product' => $product,
                'topic' => $topic,
            ], [
                'title' => $this->setTitle('Watch Course'),
            ]);
        }

        return redirect(\URL::previous());
    }

    public function groupInvitations()
    {
        $invitations = $this->invitedMemberRepository()->getGroupInvitation('community_group');

        return $this->render('user.group-invitations', [
            'invitations' => $invitations,
        ], [
            'title' => $this->setTitle('Group Invitations'),
        ]);
    }

    public function comCompetitions()
    {
        $sorttype = 'cmdashboardposts';
        $communitySlug = \Request::segment(2);
        $cmntData = app('App\\Repositories\\CommunityRepository')->getBySlug($communitySlug);

        $competitions = $this->communityCompetitionRepository()->getCompetitionActive($cmntData->id);

        return $this->render('user.home.competitions', [
            'pageHeading' => 'Competitons',
            'competitions' => $competitions,
            'community' => $cmntData,
        ], [
            ['title' => $this->setTitle('Competitions')],
        ]);
    }

    public function myAppointmentDetails(Request $request)
    {
        $userid = \Auth::user()->id;
        $adate = $request->get('adate');
        $order = $request->get('order');
        $type = $request->get('type');

        // $appointments=$this->appointmentRepository()->myAppointmentDetails($userid);

        if ($type == 1) {
            $appointments = $this->appointmentRepository()->myAllAppointmentsPersonal($userid);
        } elseif ($type == 2) {
            $appointments = $this->appointmentRepository()->myAllAppointmentsBusiness($userid);
        } elseif ($type == 3) {
            $appointments = $this->appointmentRepository()->myAllAppointmentsOrganizing($userid);
        } else {
            $appointments = $this->appointmentRepository()->myAllAppointmentDetails($userid, $adate, $order);
        }

        $resume = \Auth::user()->present()->isResumeCreated($userid);
        $setting = $this->appointmentAvailabilityRepository()->getByUser($userid);

        return $this->render('user.appointments.my-appointments', [
            'appointments' => $appointments,
            'resume' => $resume,
            'setting' => $setting,
        ], [
            'title' => $this->setTitle('My Appointments'),
        ]);
    }

    public function myAppointments()
    {
        $userid = \Auth::user()->id;

        $resume = \Auth::user()->present()->isResumeCreated();
        if (! $resume) {

            $fields = $this->customFieldRepository()->listAll('profile');
            $cityName = '';
            $stateName = '';

            foreach ($fields as $field) {
                if ($field->name == 'Current city name') {
                    $cityName = \Auth::user()->present()->profile($field->id);
                }

                if ($field->name == 'State or Province name') {
                    $stateName = \Auth::user()->present()->profile($field->id);
                }
            }

            $val = [
                'fullname' => \Auth::user()->fullname,
                'city' => $cityName,
                'state' => $stateName,
                'email' => \Auth::user()->email_address,
                'self_created' => 0,
                'is_student' => 0,
            ];
            $resume = $this->resumeRepository()->create($val);
        }

        $appointments = $this->appointmentRepository()->getMyAllAppointments($userid);

        $myTimeSettings = $this->appointmentAvailabilityRepository()->getByUser($userid);
        $myTimeZone = 'America/New_York';

        if ($myTimeSettings) {
            $myTimeZone = $myTimeSettings->timezone;
        }

        $calendarEventsList = [];
        if ($appointments) {
            foreach ($appointments as $appointment) {

                $eventName = str_replace(["\n", "\r", '<br>', '</br>', '</ br>'], '', $appointment->description);

                $color = '#000';

                if ($appointment->community_category_id == 0) {
                    $eventEditId = $appointment->id;
                } else {
                    $eventEditId = 0;
                }
                // $startTime=$appointment->appointment_date." ".$appointment->master_start_time;
                // $endTime=$appointment->appointment_date." ".$appointment->master_end_time;

                $startTime = appointmentTimeConvert($appointment->appointment_date.' '.$appointment->master_start_time, $appointment->master_timezone, $myTimeZone);

                $endTime = date('Y-m-d h:i A', strtotime('+'.$appointment->totalmins.'minutes', strtotime($startTime)));

                $url = \URL('icsfileowner/download').'/'.$appointment->id;

                if ($appointment->user_id == $userid) {
                    // $eventEditId=0;
                    $color = '#ed1b23';
                    $startTime = $appointment->appointment_date.' '.$appointment->start_time;
                    $endTime = $appointment->appointment_date.' '.$appointment->end_time;
                    $url = \URL('icsfileuser/download').'/'.$appointment->id;
                }

                if ($appointment->to_user == $userid) {
                    if ($appointment->meeting_booking_type == 2) {
                        $color = '#0BC3FB';
                    }
                }

                $startTimeFormated = date('Y-m-d H:i', strtotime($startTime));
                $endTimeFormated = date('Y-m-d H:i', strtotime($endTime));

                $calendarEventsList[] = [
                    'id' => $eventEditId,
                    'title' => preg_replace('/[^A-Za-z0-9 \-]/', '', $eventName),  // $appointment->description
                    'start' => $startTimeFormated,
                    'end' => $endTimeFormated,
                    'color' => $color,
                    // 'url'=> $url,
                ];
            }
        }

        $datesEvent = json_encode($calendarEventsList, true);

        return $this->render('user.appointments.my-calendar', [
            'appointments' => $appointments,
            'datesEvent' => $datesEvent,
            'resume' => $resume,
        ], [
            'title' => $this->setTitle('My Appointments'),
        ]);
    }

    public function myCalEvents()
    {
        $userid = \Auth::user()->id;
        // $appointments=$this->appointmentRepository()->myAppointments($userid);
        $appointments = $this->appointmentRepository()->getMyAllAppointments($userid);

        return $this->render('user.appointments.my-calevents', ['appointments' => $appointments]);
    }

    public function myEventImported(Request $request)
    {
        $userid = \Auth::user()->id;
        $message = $request->get('message');

        return $this->render('user.appointments.my-eventimported', ['message' => $message]);
    }

    public function suggestAttendee(Request $request)
    {
        $term = $request->get('term');
        $strArray = explode(',', $term);
        $term = end($strArray);

        $term = trim($term);

        $result = [
            'code' => 0,
            'message' => '',
        ];

        $users = $this->userRepository()->searchUsers($term);

        if (! empty($users)) {
            $result['code'] = 1;
            $result['content'] = (string) $this->theme->section('user.appointments.suggest-attendee', ['users' => $users]);
        }
        echo json_encode($result);
    }

    public function suggestUsers(Request $request)
    {
        $term = $request->get('term');
        $strArray = explode(',', $term);
        $term = end($strArray);

        $term = trim($term);

        $result = [
            'code' => 0,
            'message' => '',
        ];

        $users = $this->userRepository()->searchAllUsers($term);

        if (! empty($users)) {
            $result['code'] = 1;
            $result['content'] = (string) $this->theme->section('user.appointments.suggest-attendee', ['users' => $users]);
        }
        echo json_encode($result);
    }

    public function connectZoom(Request $request)
    {
        $url = $request->get('url');

        return $this->render('user.zoom', ['url' => $url], [
            'title' => 'Zoom Meeting',
        ]);
    }

    public function changePickupDate(Request $request)
    {
        $id = $request->get('id');
        $value = $request->get('value');

        $order = $this->businessProductsOrdersRepository()->changePickupDate($id, $value);

        if ($order) {
            return '<strong>Date:</strong>'.date('d F Y', strtotime($order->order_date_time)).'<br />
            <strong>Time:</strong>'.date('H:m A', strtotime($order->order_date_time)).'<br />';
        } else {
            return '';
        }
    }

    public function editAppointment(Request $request)
    {
        $userid = \Auth::user()->id;
        $appointmentId = $request->get('eventId');

        $appointment = $this->appointmentRepository()->getById($appointmentId);
        if ($appointment->user_id == $userid || $appointment->to_user == $userid) {
            return $this->theme->section('user.appointments.edit-event', ['appointment' => $appointment, 'userid' => $userid]);
        }

        return 0;
    }

    public function getAppointmentDetails(Request $request)
    {
        $userid = \Auth::user()->id;
        $appointmentId = $request->get('eventId');

        $appointment = $this->appointmentRepository()->getById($appointmentId);
        if ($appointment->user_id == $userid || $appointment->to_user == $userid) {
            $adate = '';

            $myTimeSettings = $this->appointmentAvailabilityRepository()->getByUser(\Auth::user()->id);
            $myTimeZone = 'America/New_York';

            if ($myTimeSettings) {
                $myTimeZone = $myTimeSettings->timezone;
            }

            return $this->theme->section('user.appointments.appointment-details', ['appointment' => $appointment, 'i' => 1, 'adate' => $adate, 'myTimeZone' => $myTimeZone]);
        }

        return 0;
    }

    public function changeAppointmentStatus(Request $request)
    {
        $userid = \Auth::user()->id;

        $appointmentId = $request->get('id');
        $value = $request->get('val');

        $appointment = $this->appointmentRepository()->getById($appointmentId);
        if ($appointment->to_user == $userid) {
            $appointment->meeting_booking_type = $value;
            $appointment->save();

            $appointments = $this->appointmentRepository()->getMyAllAppointments($userid);

            $myTimeSettings = $this->appointmentAvailabilityRepository()->getByUser($userid);
            $myTimeZone = 'America/New_York';

            if ($myTimeSettings) {
                $myTimeZone = $myTimeSettings->timezone;
            }

            $calendarEventsList = [];
            if ($appointments) {
                foreach ($appointments as $appointment) {

                    $eventName = str_replace(["\n", "\r", '<br>', '</br>', '</ br>'], '', $appointment->description);

                    $color = '#000';

                    if ($appointment->community_category_id == 0) {
                        $eventEditId = $appointment->id;
                    } else {
                        $eventEditId = 0;
                    }

                    $startTime = appointmentTimeConvert($appointment->appointment_date.' '.$appointment->master_start_time, $appointment->master_timezone, $myTimeZone);

                    $endTime = date('Y-m-d h:i A', strtotime('+'.$appointment->totalmins.'minutes', strtotime($startTime)));

                    $url = \URL('icsfileowner/download').'/'.$appointment->id;

                    if ($appointment->user_id == $userid) {
                        $color = '#ed1b23';
                        $startTime = $appointment->appointment_date.' '.$appointment->start_time;
                        $endTime = $appointment->appointment_date.' '.$appointment->end_time;
                        $url = \URL('icsfileuser/download').'/'.$appointment->id;
                    }

                    if ($appointment->to_user == $userid) {
                        if ($appointment->meeting_booking_type == 2) {
                            $color = '#0BC3FB';
                        }
                    }

                    $startTimeFormated = date('Y-m-d H:i', strtotime($startTime));
                    $endTimeFormated = date('Y-m-d H:i', strtotime($endTime));

                    $calendarEventsList[] = [
                        'id' => $eventEditId,
                        'title' => preg_replace('/[^A-Za-z0-9 \-]/', '', $eventName),  // $appointment->description
                        'start' => $startTimeFormated,
                        'end' => $endTimeFormated,
                        'color' => $color,
                    ];
                }
            }

            $datesEvent = json_encode($calendarEventsList, true);

            return $datesEvent;
        }
    }

    public function topicEditAppointment(Request $request)
    {
        $userid = \Auth::user()->id;
        $appointmentId = $request->get('eventId');

        $appointment = $this->appointmentRepository()->getById($appointmentId);
        if ($appointment->category_dept_id != 0) {
            return $this->theme->section('community.page.appointment.edit-event', ['appointment' => $appointment, 'userid' => $userid]);
        }

        return 0;
    }

    public function generateIdmeetMeeting()
    {
        $result = $this->appointmentRepository()->generateIdmeetUrl();

        return json_encode($result);
    }

    public function userIdentification()
    {
        $userid = \Auth::user()->id;
        $identification = $this->userIdentificationRepository()->getByUserId($userid);

        return $this->render('user.identification.index', ['identification' => $identification]);
    }

    public function uploadDocuments(Request $request)
    {
        $type = $request->get('type');
        $value = $request->get('value');
        $identitifcation = $this->userIdentificationRepository()->uploadDocuments($type);

        $canShow = 0;
        if ($value == 'identity') {
            if ($identitifcation->identity_document != '' and $identitifcation->identity_document_back != '') {
                $canShow = 1;
            }
        } elseif ($value == 'address') {
            if ($identitifcation->address_document != '' and $identitifcation->address_document_back != '') {
                $canShow = 1;
            }
        } elseif ($value == 'photo') {
            if ($identitifcation->photo_document != '' and $identitifcation->photo_document_back != '') {
                $canShow = 1;
            }
        }

        return $canShow;
    }

    public function saveIdentification(Request $request)
    {
        $val = $request->get('val');

        return $this->userIdentificationRepository()->saveIdentification($val);
    }

    public function saveIdentificationAddress(Request $request)
    {
        $val = $request->get('val');

        return $this->userIdentificationRepository()->saveIdentificationAddress($val);
    }

    public function saveIdentificationPhoto()
    {
        return $this->userIdentificationRepository()->saveIdentificationPhoto();
    }

    public function verifyUsers(Request $request)
    {
        if (\Auth::user()->identity_admin == 1) {
            $type = $request->get('type');
            $term = $request->get('term');

            $identifications = $this->userIdentificationRepository()->getAll($type, $term);

            return $this->render('user.identification.verification.index', ['identifications' => $identifications]);
        } else {
            return \Redirect::route('user-home');
        }
    }

    public function viewDocument(Request $request)
    {

        $type = $request->get('type');
        $id = $request->get('id');

        if (\Auth::user()->identity_admin == 1) {
            $identification = $this->userIdentificationRepository()->getById($id);

            if ($identification) {
                return $this->theme->section('user.identification.verification.view-document', ['identification' => $identification, 'type' => $type]);
            }
        }
    }

    public function identificationStatus(Request $request)
    {
        $id = $request->get('id');
        $status = $request->get('status');
        $comment = $request->get('comment');

        $identityexpiry = $request->get('identityexpiry');
        $nationality = $request->get('nationality');
        $birthplace = $request->get('birthplace');
        $gender = $request->get('gender');
        $addressidentity = $request->get('addressidentity');
        $addressidentityissued = $request->get('addressidentityissued');

        if (\Auth::user()->identity_admin == 1) {
            return $identification = $this->userIdentificationRepository()->identificationStatus($id, $status, $comment, $identityexpiry, $nationality, $birthplace, $gender, $addressidentity, $addressidentityissued);
        }
    }

    public function identificationInfoChange(Request $request)
    {
        $val = $request->get('val');

        if (\Auth::user()->identity_admin == 1) {
            return $identification = $this->userIdentificationRepository()->identificationInfoChange($val);
        }
    }

    public function loadIdentityDocs(Request $request)
    {
        $id = $request->get('id');
        if (\Auth::user()->identity_admin == 1 || \Auth::user()->admin == 1) {
            $identification = $this->communityRepository()->getById($id);

            if ($identification) {

                if ($identification->pin == 0) {
                    $identification->pin = rand(1000, 9999);
                    $identification->save();
                }

                if ($identification->unique_key == '') {
                    $identification->unique_key = $this->userIdentificationRepository()->uniqueIdentity();
                    $identification->save();
                }

                return $this->theme->section('user.identification.verification.view-document-all', ['identification' => $identification]);
            }
        }
    }

    public function previewIdentityData(Request $request)
    {
        $id = $request->get('id');
        if (\Auth::user()->identity_admin == 1) {
            $identification = $this->userIdentificationRepository()->getById($id);

            if ($identification) {
                return $this->theme->section('user.identification.verification.document-preview', ['identi' => $identification]);
            }
        }
    }

    public function searchPrimaryCommunity(Request $request)
    {
        $keyword = $request->get('keyword');
        $communities = $this->communityRepository()->searchByName($keyword);

        return $this->theme->section('user.home.community-listing', ['communities' => $communities]);
    }

    public function requestPrimaryCommunity(Request $request)
    {
        $id = $request->get('id');
        $this->communityPrimaryMembersRepository()->add($id);
    }

    public function setPrimaryFavourite(Request $request)
    {
        $communityId = $request->get('cmid');
        $this->userRepository()->setPrimaryFavourite($communityId);
    }

    public function askReuploadDocument(Request $request)
    {
        $id = $request->get('id');
        $type = $request->get('type');
        $reason = $request->get('reason');

        if (\Auth::user()->identity_admin == 1 || \Auth::user()->admin == 1) {
            $identification = $this->userIdentificationRepository()->askReuploadDocument($id, $type, $reason);
        }
    }

    public function viewIdentityKey(Request $request)
    {
        $identity_pin = $request->get('identity_pin');
        $userid = \Auth::user()->id;
        $identity = $this->userIdentificationRepository()->getByUserId($userid);
        if ($identity and $identity->pin == $identity_pin) {
            return $identity->unique_key;
        }

        return 0;
    }

    public function identityAccess()
    {
        if (\Auth::user()->identity_access == 1) {
            return $this->render('user.identification.verification.access-identity', []);
        }

        return redirect(\URL::previous());
    }

    public function viewIdentityByKey(Request $request)
    {
        if (\Auth::user()->identity_access == 1) {

            $identity_key = $request->get('identity_key');

            $identity_key = trim($identity_key);
            $identity = $this->userIdentificationRepository()->getByKey($identity_key);

            if ($identity) {
                return $this->theme->section('user.identification.verification.access-identity-view', ['identi' => $identity]);
            }
        }

        return 0;
    }

    public function identityAccessPrint($id)
    {
        if (\Auth::user()->identity_access == 1) {
            $identity = $this->userIdentificationRepository()->getById($id);

            if ($identity) {
                return $this->render('user.identification.verification.access-identity-print', ['identi' => $identity]);
            }
        }

        return 0;
    }

    public function getSuggstedFriends(Request $request)
    {
        $id = $request->get('id');
        $posted_community = '';

        if ($id > 0) {
            $posted_community = $this->communityRepository()->getById($id);
        }

        return $this->theme->section('connection.friend.suggsted-users', ['posted_community' => $posted_community]);
    }

    public function saveSecondaryEmail(Request $request)
    {
        $email = $request->get('email');

        $result = $this->userRepository()->findByBothEmail($email);
        if ($result) {
            return 'This email address has already been taken.';
        } else {
            return $this->userRepository()->sendSecondayEmail($email);
        }
    }

    public function updateSecondaryEmail($user_id, Request $request)
    {
        $emailOriginal = $request->get('str');
        $uid = $request->get('uid');
        $eml = $request->get('eml');

        $email = base64_decode($emailOriginal);

        if ($email and $emailOriginal == $eml and $user_id == $uid) {

            $findByBothEmail = $this->userRepository()->findByBothEmail($email);
            if ($findByBothEmail) {
                $message = $email.' email has already been taken';
            } else {
                $result = $this->userRepository()->updateSecondaryEmail($user_id, $uid, $email);
                $message = "Successfully saved your seconday email '".$email."'";
            }
        } else {
            $message = 'Invalid link';
        }

        return $this->render('user.save-secondary-email', ['message' => $message]);
    }

    public function setCookie($cookie_value)
    {
        $cookie_value = base64_decode($cookie_value);

        $hostName = \Request::getHost();

        $uniqid = uniqid();
        $cookie_name = config('community-domain.cookie-name');
        $expireTime = time() + (86400 * 30);

        // header('Set-Cookie: '.$cookie_name.'='.$cookie_value.'; expires='.$expireTime.'; path=/; SameSite=None; Secure');

        if (! isset($_COOKIE[$cookie_name])) {
            $secure = config('community-domain.mode') == 'live';
            
            // Use Laravel's Cookie facade instead of setcookie()
            $cookie = cookie($cookie_name, $cookie_value, $expireTime / 60, '/', $hostName, $secure, true);
            
            // Queue the cookie to be sent with the response
            \Cookie::queue($cookie);
        }

        $this->userSessionsRepository()->sessionVerification($cookie_value);
    }

    public function unsetCookie($cookie_name)
    {
        try {
            $cookie_name = base64_decode($cookie_name);
            $hostName = \Request::getHost();
            $secure = config('community-domain.mode') == 'live';
            
            // Create the cookie to expire it
            $cookie = cookie($cookie_name, '', -2628000, '/', $hostName, $secure, true);
            
            // Create response and attach cookie
            $response = response('Cookie unset successfully');
            return $response->withCookie($cookie);
            
        } catch (\Exception $e) {
            \Log::error('Error in unsetCookie: ' . $e->getMessage());
            return response()->json(['error' => 'Cookie unset failed'], 500);
        }
    }

    public function logoutCookie()
    {
        // return clearUserSession();
        return $this->userSessionsRepository()->clearUserSession();
    }

    public function userSetSiteInfo()
    {
        return $this->userSessionsRepository()->userSetSiteInfo();
    }

    public function getCityCampaignView(Request $request)
    {
        $id = $request->get('id');
        $code = $request->get('code');
        $name = $request->get('name');

        $campaign = $this->communityCampaignRepository()->getById($id);
        if ($campaign and $campaign->user_id == \Auth::user()->id) {
            return $this->theme->section('community.pannel.campaigns.campaign-city-report', ['campaign' => $campaign, 'code' => $code, 'name' => $name]);
        } else {
            return '';
        }
    }

    public function checkMySmtp(Request $request)
    {
        $smtp_details = $this->userSettingsRepository()->getByUserId();
        $to = $request->get('email');

        if ($to) {
            $mailManager = app(\Illuminate\Mail\MailManager::class);

            $originalSmtpMailerConfig = [
                'host' => config('mail.mailers.smtp.host'),
                'port' => config('mail.mailers.smtp.port'),
                'scheme' => config('mail.mailers.smtp.scheme'),
                'url' => config('mail.mailers.smtp.url'),
                'username' => config('mail.mailers.smtp.username'),
                'password' => config('mail.mailers.smtp.password'),
            ];

            $port = (int) ($smtp_details->smtp_mail_driver_port ?? 0);
            $encryption = strtolower(trim((string) ($smtp_details->mail_driver_encryption ?? '')));
            $scheme = null;
            if ($encryption === 'ssl' || $encryption === 'smtps' || (($encryption === '' || $encryption === 'tls') && $port === 465)) {
                $scheme = 'smtps';
            }

            \Config::set('mail.mailers.smtp.host', $smtp_details->smtp_mail_driver_host);
            \Config::set('mail.mailers.smtp.port', $port);
            \Config::set('mail.mailers.smtp.username', $smtp_details->smtp_username);
            \Config::set('mail.mailers.smtp.password', $smtp_details->smtp_password);
            \Config::set('mail.mailers.smtp.scheme', $scheme);
            \Config::set('mail.mailers.smtp.url', null);

            $mailManager->forgetMailers();
            $mailerToUse = $mailManager->mailer('smtp');

            $from_name = $smtp_details->mail_from_name;
            $from_email = $smtp_details->mail_from_email;

            $replyto_name = $smtp_details->mail_from_name;
            $replyto_email = $smtp_details->mail_from_email;

            $subject = 'Outbound Email Setting Test';
            try {

                $mailerToUse->send('emails.smtp-test-email', [

                ], function ($mail) use ($to, $subject, $from_name, $from_email, $replyto_name, $replyto_email) {

                    $mail->to($to)
                        ->replyTo($replyto_email, $replyto_name)
                        ->subject($subject)
                        ->from($from_email, $from_name);
                });
            } catch (\Exception $e) {
                foreach ($originalSmtpMailerConfig as $key => $value) {
                    \Config::set("mail.mailers.smtp.{$key}", $value);
                }
                $mailManager->forgetMailers();
                return 'Invalid details, recheck your details and try again';
            }

            foreach ($originalSmtpMailerConfig as $key => $value) {
                \Config::set("mail.mailers.smtp.{$key}", $value);
            }
            $mailManager->forgetMailers();

            return 'Email sent successfully, check your email inbox.';

        }

        return 'Provide email address to test ';
    }

    public function sendCampaignEmail(Request $request)
    {
        $dataId = $request->get('dataId');
        $this->communityCampaignEmailsRepository()->sendEmails($dataId);

        return json_encode([
            'sending' => $this->communityCampaignEmailsSentRepository()->getSentCount($dataId),
            'pending' => $this->communityCampaignEmailsSentRepository()->getUnsentCount($dataId),
        ]);
    }

    public function primaryCmTakeAction(Request $request)
    {
        $value = $request->get('value');
        $smtp_details = $this->userSettingsRepository()->primaryCmTakeAction($value);
    }

    public function enterToSubmit(Request $request)
    {
        $value = $request->get('value');
        $this->userSettingsRepository()->enterToSubmit($value);
    }

    public function importIcsAppointments()
    {

        // require_once app_path().'/library/iCal/icalendar.php';

        require_once base_path('functions/iCal/icalendar.php');

        $ical = new \iCalendar;

        $filename = $_FILES['ics-file']['tmp_name'];
        $ical->parse("$filename");
        $ical_data = $ical->get_all_data();

        /*if(isset({$ical_data['VCALENDAR']['X-WR-TIMEZONE']})){
            $timezone = "{$ical_data['VCALENDAR']['X-WR-TIMEZONE']}";
        }else{*/

        $user_id = \Auth::user()->id;

        $timezone = '';
        $setting = $this->appointmentAvailabilityRepository()->getByUser($user_id);
        if ($setting and $setting->timezone) {
            $timezone = $setting->timezone;
        }

        if ($timezone == '') {
            if (\Session::has('user_client_timezone')) {
                $timezone = \Session::get('user_client_timezone');
            } else {
                $timezone = 'America/New_York';
            }
        }

        /* } */
        if (function_exists('date_default_timezone_set')) {
            date_default_timezone_set($timezone);
        }

        if (! empty($ical_data['VEVENT'])) {
            foreach ($ical_data['VEVENT'] as $key => $data) {

                // get StartDate And StartTime
                $start_dttimearr = explode('T', $data['DTSTART']);
                $StartDate = $start_dttimearr[0];
                $startTime = $start_dttimearr[1];

                // get EndDate And EndTime
                $end_dttimearr = explode('T', $data['DTEND']);
                $EndDate = $end_dttimearr[0];
                $EndTime = $end_dttimearr[1];

                $description = '';
                $location = '';

                if (isset($data['DESCRIPTION'])) {
                    $description = $data['DESCRIPTION'];
                    // $description=str_replace('\r',"",$description);
                    $description = str_replace('\n', '<br>', $description);
                }

                if (isset($data['LOCATION'])) {
                    $location = $data['LOCATION'];
                    // $location=str_replace('\r',"</ br>",$location);
                    $location = str_replace('\n', '<br>', $location);
                }

                $StartDate = date('Y-m-d', strtotime($StartDate));

                $to_time = strtotime($startTime);
                $from_time = strtotime($EndTime);
                $totalmins = round(abs($to_time - $from_time) / 60, 2);

                $appointment = $this->appointmentRepository()->model->newInstance();

                $appointment->user_id = \Auth::user()->id;
                $appointment->to_user = 0;

                $appointment->appointment_date = $StartDate;
                $appointment->totalmins = $totalmins;

                $appointment->start_time = date('h:i A', strtotime($startTime));
                $appointment->end_time = date('h:i A', strtotime($EndTime));
                $appointment->time_zone = $timezone;

                $appointment->master_start_time = date('h:i A', strtotime($startTime));
                $appointment->master_end_time = date('h:i A', strtotime($EndTime));
                $appointment->master_timezone = $timezone;

                $appointment->description = $description;

                $appointment->location = $location;
                $appointment->save();

                if ($appointment) {
                    $this->appointmentBookingRepository()->addBooking($user_id, $appointment->id, $appointment->appointment_date, $appointment->master_start_time, $appointment->master_end_time, 1);
                }
            }
        }
    }

    public function cancelledAppointments(Request $request)
    {
        $userid = \Auth::user()->id;
        $adate = $request->get('adate');
        $order = $request->get('order');

        $appointments = $this->appointmentRepository()->myAllAppointmentDetailsCancelled($userid, $adate, $order);
        $resume = \Auth::user()->present()->isResumeCreated($userid);
        $setting = $this->appointmentAvailabilityRepository()->getByUser($userid);

        return $this->render('user.appointments.my-appointments', [
            'appointments' => $appointments,
            'resume' => $resume,
            'setting' => $setting,
        ], [
            'title' => $this->setTitle('My Appointments'),
        ]);
    }

    public function getMeetingDetails(Request $request)
    {
        $id = $request->get('id');
        $appointment = $this->appointmentRepository()->getById($id);

        $meetingDate = '';
        $note = '';
        $total_time = '';
        $location = '';
        $emails = '';

        if ($appointment) {
            $meetingDate = $appointment->appointment_date;
            $note = $appointment->description;
            $total_time = $appointment->totalmins;
            $location = $appointment->location;

            if ($appointment->user_id == \Auth::user()->id) {
                $emails = \Auth::user()->email_address;
            } else {
                $user = $this->userRepository()->findByIdUsername($appointment->user_id);
                if ($user) {
                    $emails = $user->email_address;
                } else {
                    $emails = $appointment->email;
                }
            }

            $appointments = $this->appointmentRepository()->getByAppointmentId($id);

            if ($appointments) {
                if ($emails) {
                    $emails = $emails.',';
                }

                foreach ($appointments as $apt) {
                    if ($apt->user_id == \Auth::user()->id) {
                        $emails .= \Auth::user()->email_address.',';
                    } else {
                        $user = $this->userRepository()->findByIdUsername($apt->user_id);
                        if ($user) {
                            $emails .= $user->email_address.',';
                        } else {
                            $emails .= $apt->email.',';
                        }
                    }
                }
            }
        }

        return json_encode([
            'meeting_date' => $meetingDate,
            'note' => $note,
            'total_time' => $total_time,
            'location' => $location,
            'emails' => $emails,
        ]);
    }

    public function searchByEmailAdrs(Request $request)
    {
        $email_address = $request->get('email_address');
        $user = $this->userRepository()->findByBothEmail($email_address);
        if ($user) {
            return 1;
        } else {
            return 0;
        }
    }

    public function additionalPage($slug)
    {
        $page = $this->additionalPageRepository()->getBySlug($slug);
        if ($page->activate == 1) {
            if (\Auth::check()) {
                return $this->theme->view('community.pages.additional-page', ['page' => $page])->render();
            } else {
                return \Redirect::route('pg-additional-page', ['slug' => $slug]); // ----
            }
        } else {
            return $this->theme->view('error-page');
        }
    }

    public function myRideBooking()
    {$userid = \Auth::user()->id;
        $myRides = $this->communityPricingPlanPaymentRepository()->getMyRidingPayments($userid);

        return $this->render('user.purchase.my-rides', [
            'myRides' => $myRides,
        ], [
            'title' => $this->setTitle('My Rides'),
        ]);
    }

    public function changeMyPaymentCard($type, $type_id)
    {
        return $this->render('community.pannel.plan.change-card', [
            'type' => $type,
            'type_id' => $type_id,
        ], [
            'title' => $this->setTitle('Change Card'),
        ]);
    }

    public function viewMyInvoice($type, $type_id)
    {
        $record = '';
        if ($type == 'plans_payments') {
            $record = $this->communityPricingPlanPaymentRepository()->getById($type_id);
        } elseif ($type == 'plans_invoice') {
            return $pendingInvoice = $this->communityInvoiceRepository()->pendingSubscriptionInvoice($type_id);
        }

        return $this->render('user.view-invoice', [
            'type' => $type,
            'type_id' => $type_id,
            'invoice' => $record,
        ], [
            'title' => $this->setTitle('View Invoice'),
        ]);
    }

    public function downloadMyInvoice($type, $type_id)
    {
        if ($type == 'plans_payments') {
            return $record = $this->communityPricingPlanPaymentRepository()->getById($type_id);
        }
    }
	
	public function userApps()
	{
		//$myOrgCreated=\Auth::user()->present()->isMyCommunityCreated(); 
		$myOrgCreated=\Auth::user()->present()->myCommunityCreated(); 
		if(!$myOrgCreated){
			//$this->featuresRepository()->getAllActive()
			return $this->render('user.home.apps', ['features' => $this->pricingPlansFeaturesRepository()->getAllActive()
			], [
				'title' => $this->setTitle('View Apps'),
			]);
		}
		return redirect('/home');			
	}
	
	public function userAppsCategories()
	{
		//$myOrgCreated=\Auth::user()->present()->isMyCommunityCreated(); 
		
		$plans=$this->pricingPlansRepository()->getInsidePlans();
		
		$myOrgCreated=\Auth::user()->present()->myCommunityCreated(); 
		if(!$myOrgCreated){
			return $this->render('user.home.apps-categories', ['plans'=>$plans], [
				'title' => $this->setTitle('View Apps'),
			]);
		}
		return redirect('/home');			
	}
	
	public function userPlanSignup($pid)
	{
		$plan=$this->pricingPlansRepository()->getPlanByPlanId($pid);				
		$myOrgCreated=\Auth::user()->present()->myCommunityCreated(); 
		if(!$myOrgCreated and $plan){
			return $this->render('user.home.plan-signup', [
				'plan'=>$plan,
				'myOwnedCommunity'=>''
			], [
				'title' => $this->setTitle(''),
			]);
		}	
		return redirect('/home');	
	}
	
	public function userFeatureSignup($fid)
	{
		$feature=$this->featuresRepository()->getById($fid);				
		return $this->render('user.home.feature-signup', [
			'feature'=>$feature
        ], [
            'title' => $this->setTitle(''),
        ]);
	}
	
	public function loadPost(Request $request, $postId)
    {
        try {
            $post = $this->postRepository()->findById($postId);
            
            if (!$post || !$post->present()->canShow()) {
                return response()->json(['error' => 'Post not found'], 404);
            }
            
            $accessCommunityId = $request->input('accessCommunityId', '');
            $accessCategoryId = $request->input('accessCategoryId', '');
            $communityOwnerActions = $request->input('communityOwnerActions', '');
            $communityOwner = $request->input('communityOwner', '');
            $singlePost = $request->input('singlePost', '');
            $ownership = $request->input('ownership', '');
            
            $postContent = (String) \Theme::section('post.media', [
                'post' => $post,
                'accessCommunityId' => $accessCommunityId,
                'accessCategoryId' => $accessCategoryId,
                'communityOwnerActions' => $communityOwnerActions,
                'communityOwner' => $communityOwner,
                'singlePost' => $singlePost,
                'ownership' => $ownership
            ]);
            
            return response($postContent);
            
        } catch (\Exception $e) {
           // \Log::error('Error loading post: ' . $e->getMessage());
            return response()->json(['error' => 'Error loading post'], 500);
        }
    }

    public function cbDashboard()
    {		       
		$userid = \Auth::user()->id;
		 
		//$upcomingMeetings=''; 
		$upcomingMeetings=$this->appointmentRepository()->myAllUpcomingAppointments($userid);
		$myTimeSettings = $this->appointmentAvailabilityRepository()->getByUser($userid);        
		$revenue=$this->businessProductsOrdersRepository()->getMyRevenue($userid); 
		$active_customers=$this->businessProductsOrdersRepository()->getMyCustomers($userid); 
		
		$myTimeZone = 'America/New_York';

        if ($myTimeSettings) {
            $myTimeZone = $myTimeSettings->timezone;
        }
		
		
        
		//$geographic=0;
		//$uniqueVisitorsCount=0;
		//$geographicCountriesNames=array();
		
		
		$geographic=$this->siteVisitorsDataRepository()->getCountAllType('socialprofile',\Auth::user()->id, 'allcountries', 'allcountries');
		   ;
		$uniqueVisitorsCount=$this->siteVisitorsDataRepository()->getCountAllType('socialprofile',\Auth::user()->id, 'unique_visitors', 'unique_visitors');
		
		$geographicCountriesNames=$this->siteVisitorsDataRepository()->geographicCountriesNamesAllType('socialprofile',\Auth::user()->id);   		       
		
		$resume_id='';	
			
		$hasResumeCreated=\Auth::user()->present()->isResumeCreated(\Auth::user()->id);
		
		if($hasResumeCreated){
           $resume_id=$hasResumeCreated->id;	
		   
		   $geographic_r = $this->siteVisitorsDataRepository()->getCountAllType('resume',$resume_id, 'allcountries', 'allcountries');
		   
		   $geographic+=$geographic_r;

           $uniqueVisitorsCount_r = $this->siteVisitorsDataRepository()->getCountAllType('resume',$resume_id, 'unique_visitors', 'unique_visitors');
		   
		   $uniqueVisitorsCount+=$uniqueVisitorsCount_r;

           $geographicCountriesNames_r = $this->siteVisitorsDataRepository()->geographicCountriesNamesAllType('resume',$resume_id);   		       
		   $geographicCountriesNames=array_merge($geographicCountriesNames,$geographicCountriesNames_r); 		   
        }
				
		$my_stores_ids=$this->pageRepository()->getByBusinesIds(\Auth::user()->id);
        if($my_stores_ids){
           foreach($my_stores_ids as $store_id){		   		
				$geographic_st = $this->siteVisitorsDataRepository()->getCountAllType('business',$store_id, 'allcountries', 'allcountries');
				
				$geographic+=$geographic_st;

           		$uniqueVisitorsCount_st = $this->siteVisitorsDataRepository()->getCountAllType('business',$store_id, 'unique_visitors', 'unique_visitors');
				
				$uniqueVisitorsCount+=$uniqueVisitorsCount_st;

           		$geographicCountriesNames_st = $this->siteVisitorsDataRepository()->geographicCountriesNamesAllType('business',$store_id);  
				
				$geographicCountriesNames=array_merge($geographicCountriesNames,$geographicCountriesNames_st); 					  
		   }
        }
				
		$my_followers=$this->connectionRepository()->followersIds(\Auth::user()->id);		
		$customer_ids=$this->businessProductsOrdersRepository()->getMyCustomerIds($userid); 
		
		// Convert collections to arrays
		$my_followers_array = $my_followers->toArray();
		$customer_ids_array = $customer_ids->toArray();
		
		// Get common IDs
		$common_ids = array_intersect($my_followers_array, $customer_ids_array);
		
		// Count total followers and common IDs
		$total_followers = count($my_followers_array);
		$common_count = count($common_ids);
		
		// Avoid division by zero
		$percentage = $total_followers > 0 ? ($common_count / $total_followers) * 100 : 0;
		
		// Optional: Round to 2 decimal places
		$cust_percentage = round($percentage, 2);
				
	    $timeline_posts=$this->postRepository()->getMyLatestTimelinePosts(\Auth::user()->id);
				
	    return $this->render('user.cb-dashboard', ['upcomingMeetings'=>$upcomingMeetings,'myTimeZone'=>$myTimeZone,'revenue'=>$revenue,'active_customers'=>$active_customers,'geographic'=>$geographic,'uniqueVisitorsCount'=>$uniqueVisitorsCount,'geographicCountriesNames'=>$geographicCountriesNames,'cust_percentage'=>$cust_percentage,'timeline_posts'=>$timeline_posts], [
            'title' => $this->setTitle('Collaboration Dashboard'),
        ]);
    }
}