<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | This page is for user section management. Login checking , new user registration, user listing etc.                                      |
// | File name : index.php                                                  |
// | PHP version >= 5.2                                                   |
// | Created On	: 	Nov 17 2011                                               |
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------


class ControllerIndex extends BaseController {
    /*
      construction function. we can initialize the models here
     */

    public function init() {
        parent::init();
        PageContext::$response->activeSubMenu = '';
        PageContext::$response->flagDisplay = 0;
        PageContext::$response = new stdClass();
        PageContext::$response->ImagePath = IMAGE_MAIN_URL;
        PageContext::$response->userImagePath = USER_IMAGE_URL;
        PageContext::$response->baseUrl = BASE_URL;
        PageContext::$response->siteName = SITE_NAME;
        PageContext::$response->sitelogo = SITE_LOGO;
        PageContext::$response->innerlogo = INNER_LOGO;
        PageContext::$response->curYear = date('Y');
        PageContext::$response->defaultImage = USER_IMAGE_URL_DEFAULT;
        PageContext::$response->themeImage = THEME_IMAGE_URL;
        PageContext::$response->isFBEnabled = FB_ENABLED;
        PageContext::$response->sess_user_id = Utils::getAuth('user_id');
        PageContext::$response->sess_user_status = Utils::getAuth('user_status');
        PageContext::$response->sess_user_name = (Utils::getAuth('user_id') > 0) ? Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname') : '';
        PageContext::$response->sess_user_fname = Utils::getAuth('user_firstname');
        PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
        PageContext::$response->sess_user_email = Utils::getAuth('user_email');
        PageContext::$response->sess_user_image = Utils::getAuth('user_image_name');
        PageContext::$response->sess_user_country = Utils::getAuth('user_country');
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        $announcementCount = Communities::getAnnouncementCountByUser();
        PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
        $messageCount = Messages::getMessageCountByUser();
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
        $frndcount = Feed::getNumPendingFriendRequestByUser();
        PageContext::$response->NumFriendRequest = $frndcount[0]->user_friend_request_count;

        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("menu", "home_menu", "index", "default");
            PageContext::$response->leftMenuUsersList = User::getUserFriends1(PageContext::$response->sess_user_alias, 'N.A', 'N.A');
        } else {
            PageContext::registerPostAction("menu", "menu", "index", "default");
        }
        PageContext::registerPostAction("footer", "home_footer", "index", "default");
        PageContext::addJsVar("siteUrl", BASE_URL);
        PageContext::addScript("common.js");
        PageContext::addScript("menu.js");
        PageContext::addScript("script.js");
        PageContext::addScript('jquery.colorbox.js');
        
    }

    function useronlineactivity() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        if (PageContext::$response->sess_user_id > 0) {
            switch ($_POST['userActivityStatus']) {
                case 'Idle':
                    $userStatus = 'Idle';
                    break;
                case 'Active':
                    $userStatus = 'Online';
                    break;
                default:
                    $userStatus = 'Offline';
                    break;
            }
            //set online status
            User::setUserOnlineStatus(PageContext::$response->sess_user_id, $userStatus);
        }
        echo 'success';
        exit;
    }

    function fblogin() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        if (!empty($_GET)) {
            //check if the email is already in use
            $userEmailCount = User::checkUserEmailExists($_GET['user_email']);
            if ($userEmailCount > 0) {
                //if user exist make him login
                $objUserRes = User::fbLoginUser($_GET['user_email']);
                if ($objUserRes->status == 'SUCCESS') {
                    //=============Set Session =============
                    Utils::setSessions($objUserRes->data);
                    //set online status
                    User::setUserOnlineStatus($objUserRes->data->user_id, 'Online');
                    $_SESSION['post_login_redir_path'] = $objUserRes->data->user_alias;

                    echo '1';
                } else {
                    if ($objUserRes->status == USER_NOT_PUBLISHED) {
                        echo '2';
                    } else if ($objUserRes->status == USER_NOT_EXIST) {
                        echo '3';
                    } else {
                        echo '0';
                    }
                }
            } else {
                //register the user
                $objUserVo = new stdClass();
                $objUserVo->user_email = $_GET['user_email'];
                $objUserVo->user_firstname = $_GET['user_fbname'];
                $objUserVo->user_password = md5(time() . '_' . rand(1000, 9999)); //random pass
                $objUserVo->user_created_on = date('Y-m-d');
                $objUserVo->user_status = 'A';
                $objUserVo->user_last_login = date('Y-m-d H:i:s');
                $objUserRes = User::createUser($objUserVo);
                //=============Set Session =============
                Utils::setSessions($objUserRes->data);

                //set online status
                User::setUserOnlineStatus($objUserRes->data->user_id, 'Online');

                if ($objUserRes->status == SUCCESS) {
                    $_SESSION['post_login_redir_path'] = $objUserRes->data->user_alias;
                    echo '1';
                } else {
                    echo '0';
                }
            }
        } else {
            echo '0';
        }
        exit;
    }

    function fbloginredir() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        if (isset($_SESSION['post_login_redir_path'])) {
            $this->redirect('newsfeed/' . $_SESSION['post_login_redir_path']);
            unset($_SESSION['post_login_redir_path']);
        } else {
            $this->redirect('index');
        }
        exit;
    }

    function updatechatlist() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $response = '';
        if (!empty(PageContext::$response->leftMenuUsersList->records)) {
            foreach (PageContext::$response->leftMenuUsersList->records as $friendEntity) {
                $user_image = trim($friendEntity->file_path) == '' ? 'member_noimg.jpg' : $friendEntity->file_path;

                switch ($friendEntity->user_online_status) {
                    case 'Idle':
                        $chat_status = "la";
                        break;
                    case 'Offline':
                        $chat_status = "ma";
                        break;
                    default:
                        $chat_status = "";
                        break;
                }
                $response .= '<li><div class="display_table"><div id="profilepic" class="profilepicsec"><a href="' . PageContext::$response->baseUrl .'timeline/'. $friendEntity->user_alias . '"><span class="mediapost_pic" style="background-image: url(' . "'" . PageContext::$response->userImagePath . $user_image . "'" . ');"></span></a></div>
                              <div class="profilenamesec"><h3 class="profile_name"><a href="javascript:void(0)" onclick="chatWith(' . "'" . $friendEntity->user_alias . "'" . ',' . "'" . $friendEntity->user_firstname . "'" . ');" title="tab-Profile" id="jProfile" class="jtab " alias="' . $friendEntity->user_firstname . '">' . $friendEntity->user_firstname . '</a></h3></div>
                              <div class="picstatus"><i class="fa fa-circle ' . $chat_status . '" aria-hidden="true"></i></div></div></li>';
            }
        } else {
            $response = '<li><div class="display_table">No Friends Added Yet!</div></li>';
        }

        echo $response;
        exit;
    }

    public function index() {
        $banner = Utils::getBanners();
        if (Utils::getAuth('user_id') > 0) {
            PageContext::$response->flagDisplay = 1;
        }
        PageContext::$response->banner = $banner;
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header", "index", "default");
        }
        PageContext::registerPostAction("banner", "banner", "index", "default");
        PageContext::registerPostAction("leftcontent", "leftcontent", "index", "default");
        PageContext::registerPostAction("messagebox", "messagebox", "index", "default");
        PageContext::$response->messagebox = Messages::getPageMessage();
        /*         * ******** Slider Css and Js ****************** */
        PageContext::addScript('modernizr.custom.28468.js');
        PageContext::addStyle('nojs.css');
        /*         * ******** Slider Css and Js Ends Here ****** */
        PageContext::addScript('index.js');
        PageContext::addScript('validations_form.js');
        PageContext::$body_class = 'home';
        PageContext::$response->activeSubMenu = '';
       // echo SITELABEL;exit;
        PageContext::$response->site_label = SITELABEL;
        PageContext::$response->site_description = SITEDESCRIPTION;
        //===========================Login Form================================
        $mail = (Utils::getCookies('user_email') != '') ? Utils::getCookies('user_email') : PageContext::$request['user_email'];
        $password = (Utils::getCookies('user_password') != '') ? Utils::getCookies('user_password') : '';
        $rememberCheck = (Utils::getCookies('user_email') != '') ? 'checked' : '';

        if (PageContext::$request['btnSubmit'] == 'Log in') {
//=======Post action==============
            //echopre1($_SERVER);
            $objUserVo = Utils::arrayToObject($_POST);
            $objUserRes = User::loginUser($objUserVo);
            
            if ($objUserRes->status == 'SUCCESS' ) {
                if ($objUserRes->data->user_status == 'A'){
                    //=============Set Session =============
                    Utils::setSessions($objUserRes->data);
                    if ($objUserRes->message == 'PASSWORD_RESET') {
                    }

                    //echo $_SERVER['HTTP_REFERER'];exit;
                    $url = explode("*", $_SERVER['HTTP_REFERER']);
                    // echopre1($url);
                    if($url[1] == 'request'){
                        $this->redirect('pending-request');
                    }
                    else{
                        $this->redirect('newsfeed/' . $objUserRes->data->user_alias);
                    }
                } else {
                    Messages::setPageMessage("You can't login since you are inactive", 'error_div');
                    $this->redirect('login');   
                }

            } else {
                Messages::setPageMessage($objUserRes->message, 'error_div');
                $this->redirect('login');
            }
        }
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->user_email = $mail;
        PageContext::$response->user_password = $password;
        PageContext::$response->remember_me = $rememberCheck;

        if (PageContext::$request['btnSubmit'] == 'Sign Up') { //=========Post action========
            $validation = User::validateRegistration(PageContext::$request);
            if ($validation['error'] == 1) {
                PageContext::$response->message0 = $validation['0'];
                PageContext::$response->message1 = $validation['1'];
                PageContext::$response->message2 = $validation['2'];
                PageContext::$response->message3 = $validation['3'];
            } else {
                $unsetArray = array('btnSubmit', 'user_confirm_password', 'terms_conditions');
                $additionalParameters = array(
                    'user_password' => md5(PageContext::$request['user_passwords']),
                    'user_created_on' => date('Y-m-d')
                );
                $objUserVo = new stdClass();
                $objUserVo->user_email = PageContext::$request['user_emails'];
                $objUserVo->user_password = md5(PageContext::$request['user_passwords']);
                $objUserVo->user_created_on = date('Y-m-d');

                if (ADMIN_APPROVE_USER_AUTO == 1) {
                    $objUserVo->user_status = 'A';
                    $msg = REGISTER_SUCCESS;
                } else {
                    $objUserVo->user_status = 'I';
                    $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                }
                $objUserVo->user_last_login = date('Y-m-d H:i:s');
                $objUserRes = User::createUser($objUserVo);
                if ($objUserRes->status == SUCCESS) {//==========User Registration mail==========
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[PageContext::$request['user_emails']] = '';
                    $replaceparams['FIRST_NAME'] = $objUserRes->data->user_firstname;
                    $replaceparams['LAST_NAME'] = '';
                    $replaceparams['LOGIN_NAME'] = PageContext::$request['user_emails'];
                    $replaceparams['PASSWORD'] = PageContext::$request['user_passwords'];
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);

                    //Mail to admin
                    $adminemail = Utils::getAdminMail();
                    $mailIds1[$adminemail] = '';
                    $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                    $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                    $replaceparams['USER_EMAIL'] = PageContext::$request['user_emails'];
                    $replaceparams['SITE_NAME'] = 'BizBFriend';
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
                    Messages::setPageMessage($msg, 'success_div');
                    //================== set session===================
                    $url = explode("*", $_SERVER['HTTP_REFERER']);
                     Utils::setSessions($objUserRes->data);
                if($url[1] == 'request'){
                    $this->redirect('pending-request');
                }
                else{
                   
                    $this->redirect('newsfeed/' . $objUserRes->data->user_alias);
                }
                } else { //========== User insertion failed ==============
                    Messages::setPageMessage($objUserRes->message, 'error_div');
                }
            }
        }
        PageContext::$response->regestrationMessage = Messages::getPageMessage();
        PageContext::$response->user_emails = PageContext::$request['user_emails'];
        $page = PageContext::$request['page'];
        $itemperpage = PAGE_LIST_COUNT;
        $announcementCount = Communities::getAnnouncementCountByUser();
        PageContext::$response->announcementCount = $announcementCount[0]->cmember_announcement_count;
        $messageCount = Messages::getMessageCountByUser();
        PageContext::$response->messageCount = $messageCount[0]->user_message_count;
//        die('Dead end at index');
    }

    public function staticpages($alias) {
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        PageContext::registerPostAction("leftcontent", "staticpages", "index", "default");
        PageContext::$body_class = 'inner';
        PageContext::$response->activeSubMenu = $alias;
        PageContext::$response->pageDetails = Utils::getPage($alias);
    }

    public function login() {
        if (Utils::checkUserLoginStatus(false)) {
            $alias = Utils::getAuth('user_alias');
            $this->redirect('newsfeed/' . $alias);
        }
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        PageContext::addScript('validations_form.js');
        PageContext::registerPostAction("leftcontent", "login", "index", "default");
        PageContext::registerPostAction("signinform", "signinform", "index", "default");
        PageContext::$response->activeSubMenu = 'login';
        //===========================Login Form================================
        PageContext::$response->mail = (Utils::getCookies('user_email') != '') ? Utils::getCookies('user_email') : PageContext::$request['user_email'];
        PageContext::$response->password = (Utils::getCookies('user_password') != '') ? Utils::getCookies('user_password') : '';
        PageContext::$response->rememberCheck = (Utils::getCookies('user_email') != '') ? '1' : '0';

        if (PageContext::$request['btnSubmit'] == 'Sign in') { //=======Post action==============
            $objUserVo = Utils::arrayToObject($_POST);
            $objUserRes = User::loginUser($objUserVo);
            if ($objUserRes->status == 'SUCCESS') {

                //=============Set Session =============
                Utils::setSessions($objUserRes->data);
                if ($objUserRes->message == 'PASSWORD_RESET') {
                    $this->redirect('changepassword');
                }
                $this->redirect('newsfeed/' . $objUserRes->data->user_alias);
            } else {

                Messages::setPageMessage($objUserRes->message, 'error_div');
            }
        }
        PageContext::$response->message = Messages::getPageMessage();
        //================= Login End===============================
    }

    public function join() {
        if (Utils::checkUserLoginStatus(false)) {
            $alias = Utils::getAuth('user_alias');
            $this->redirect('timeline/' . $alias);
        }
        PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");
        PageContext::registerPostAction("leftcontent", "join", "index", "default");
        PageContext::$body_class = 'register';
        PageContext::$response->activeSubMenu = 'join';

        //================== Registration Form =============================
        $title = "I agree to the <a href='" . BASE_URL . "terms' target='_blank'>Terms of Service</a> and <a href='" . BASE_URL . "privacy-policy' target='_blank'>Privacy Policy</a>.";
        $arrFormParams = array('name' => 'frmUserRegister', 'id' => 'frmUserRegister', 'method' => 'post', 'action' => BASE_URL . 'join', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('user_firstname' => array('type' => 'text', 'name' => 'user_firstname', 'value' => PageContext::$request['user_firstname'], 'size' => 10, 'placeholder' => 'First Name',
                'label' => array('message' => '', 'class' => ''),
            ),
            'user_lastname' => array('type' => 'text', 'name' => 'user_lastname', 'value' => PageContext::$request['user_lastname'], 'size' => 10, 'class' => '', 'placeholder' => 'Last Name',
                'label' => array('message' => '', 'class' => ''),
            ),
            'user_email' => array('type' => 'text', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'user_password' => array('type' => 'password', 'name' => 'user_password', 'id' => 'user_password', 'value' => '', 'class' => '', 'placeholder' => 'Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password'), 'minlength' => array('8', 'Please enter at least 8 characters'), 'passcheck' => array('8', 'Please enter a password with an uppercase character and a numeric.')))),
            'user_confirm_password' => array('type' => 'password', 'name' => 'user_confirm_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Re-enter Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please re-enter password'), 'equalTo' => array('user_password', 'Password mismatch!')))),
            'terms_conditions' => array('type' => 'checkbox', 'name' => 'terms_conditions', 'value' => '1', 'size' => 10, 'class' => '', 'placeholder' => '', 'title' => $title,
                'label' => array('message' => '', 'class' => 'checkbox'),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please accept the terms and conditions.')))),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'signup_btn', 'value' => 'Sign Up'),
        );

        $objFormManager->addFields($arrFormElements);

        if (PageContext::$request['btnSubmit']) { //==========Post action==========
            $objValidator = new formValidator();
            $validation = $objValidator->validate($arrFormElements);
            if ($validation['error'] == 1) {
                $objFormManager->addValidationMessages($validation);
            } else {
                $unsetArray = array('btnSubmit', 'user_confirm_password', 'terms_conditions', '__utma', '__utmz', 'uvts', 'CAKEPHP');
                $additionalParameters = array(
                    'user_password' => md5(PageContext::$request['user_password']),
                    'user_created_on' => date('Y-m-d')
                );
                $objUserVo = new stdClass();
                $objUserVo->user_firstname = PageContext::$request['user_firstname'];
                $objUserVo->user_lastname = PageContext::$request['user_lastname'];
                $objUserVo->user_email = PageContext::$request['user_email'];
                $objUserVo->user_password = md5(PageContext::$request['user_password']);
                $objUserVo->user_created_on = date('Y-m-d');
                $objUserVo->user_created_on = date('Y-m-d');
                if (ADMIN_APPROVE_USER_AUTO == 1) {
                    $objUserVo->user_status = 'A';
                    $msg = REGISTER_SUCCESS;
                } else {
                    $objUserVo->user_status = 'I';
                    $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                }
                $objUserRes = User::createUser($objUserVo);

                if ($objUserRes->status == SUCCESS) {//============User Registration mail========
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[PageContext::$request['user_email']] = '';
                    $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                    $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                    $replaceparams['LOGIN_NAME'] = PageContext::$request['user_email'];
                    $replaceparams['PASSWORD'] = PageContext::$request['user_password'];
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);

                    //Mail to admin
                    $adminemail = Utils::getAdminMail();
                    $mailIds1[$adminemail] = '';
                    $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                    $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                    $replaceparams['USER_EMAIL'] = PageContext::$request['user_email'];
                    $replaceparams['SITE_NAME'] = 'BizBFriend';
                    $objMailer = new Mailer();
                    $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
                    Messages::setPageMessage($msg, 'success_div');
                    Utils::setSessions($objUserRes->data);
                    $this->redirect('account/' . $objUserRes->data->user_alias);
                } else { //========User insertion failed =======
                    Messages::setPageMessage($objUserRes->message, 'error_div');
                }
            }
        }
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->objForm = $objFormManager->renderForm();
    }

    public function lostpassword() {
        PageContext::registerPostAction("header", "header_login", "index", "default");
        PageContext::registerPostAction("leftcontent", "lostpassword", "index", "default");
        PageContext::addScript('validations_form.js');
        PageContext::$body_class = 'inner';
        PageContext::$response->activeSubMenu = $alias;
        //===============Forgot password Form ==============
        $arrFormParams = array('name' => 'frmLostPassword', 'id' => 'frmLogin', 'method' => 'post', 'action' => BASE_URL . 'lost-password', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('user_email' => array('type' => 'text', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'placeholder' => 'Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'signup_btn', 'value' => 'Continue'),
        );
        $objFormManager->addFields($arrFormElements);
        if (PageContext::$request['btnSubmit']) { //=======Post action=========
            $objValidator = new formValidator();
            $validation = $objValidator->validate($arrFormElements);

            if ($validation['error'] == 1) {
                $objFormManager->addValidationMessages($validation);
            } else {
                $objUserRes = User::resetPassword(PageContext::$request['user_email']);
                if ($objUserRes->status == 'SUCCESS') {//=======Reset mail========
                    $mailIds = array();
                    $replaceparams = array();
                    $mailIds[PageContext::$request['user_email']] = $objUserRes->data->user_firstname . ' ' . $objUserRes->data->user_lastname;
                    $replaceparams['FIRST_NAME'] = $objUserRes->data->user_firstname;
                    $replaceparams['LAST_NAME'] = $objUserRes->data->user_lastname;
                    $replaceparams['PASSWORD'] = $objUserRes->password;
                    $objMailer = new Mailer();
                    $flag = $objMailer->sendMail($mailIds, 'forgot_password', $replaceparams);
                    if ($flag == '0') {
                        Messages::setPageMessage('Mail Could not be sent', 'error_div');
                    } else {
                        Messages::setPageMessage($objUserRes->message, 'success_div');
                    }
                } else {
                    Messages::setPageMessage($objUserRes->message, 'error_div');
                }
            }
        }
        PageContext::$response->message = Messages::getPageMessage();
        PageContext::$response->objForm = $objFormManager->renderForm();
    }

   
    public function invite($type, $id) {
        if ($_REQUEST['contact_email'] != '') {
            $result = new stdClass();
            $list1 = explode(',', $_REQUEST["contacts_check"]);
            $length1 = sizeof($list1);
            if ($length1 > 0) { //==========Post action==========    			    			 
                $contactList = $_REQUEST["contact_list"];
                Logger::info($_REQUEST);
                $list = explode(',', $_REQUEST["contacts_check"]);
                Logger::info($list);
                $flag = 0;
                $message = '';
                $replaceparams = array();

                $length = sizeof($list);
                $count = 0;
                $notSendList = '';
                $notSendCount = 0;
                if ($type == 'user') {
                    for ($i = 0; $i < $length; $i++) {
                        $mailIds = array();
                        $invitations = array('invitation_type' => 'E',
                            'invitation_entity' => 'U',
                            'invitation_entity_id' => $id,
                            'invitation_sender_email' => PageContext::$response->sess_user_email,
                            'invitation_sender_id' => PageContext::$response->sess_user_id,
                            'invitation_receiver_email' => $list[$i],
                            'invitation_receiver_id' => 0,
                            'invitation_status' => 'P',
                            'mail_template' => 'invite'
                        );
                        $res = Connections::checkInvitationSentEmail(PageContext::$response->sess_user_id, $list[$i], 'U', $id);
                        if ($res == 0) {

                            $objInvitationsVo = Utils::arrayToObject($invitations);
                            $objInvitationRes = Connections::addInvitation($objInvitationsVo);
                            Logger::info($objInvitationRes);
                            if ($objInvitationRes->status != SUCCESS) {
                                $flag = 1;
                                $message = $objInvitationRes->message;
                            }
                            $replaceparams['EMAIL'] = $list[$i];
                            $replaceparams['INVITE_ID'] = $objInvitationRes->invitation_id;
                            $replaceparams['NAME'] = PageContext::$response->sess_user_name;
                            $replaceparams['IMG_URL'] = USER_IMAGE_URL_DEFAULT;
                            $replaceparams['INVITE_TYPE'] = 'join';
                            $mailIds[$list[$i]] = '';
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'invite', $replaceparams);
                            $count++;
                        } else {
                            if ($notSendCount != 0) {
                                $notSendList = $notSendList . ", ";
                            }
                            $notSendList = $notSendList . $list[$i];
                            $notSendCount++;
                        }
                    }
                } else if ($type == 'community') {
                    for ($i = 1; $i < $length; $i++) {
                        $mailIds = array();
                        $invitations = array('invitation_type' => 'E',
                            'invitation_entity' => 'C',
                            'invitation_entity_id' => $id,
                            'invitation_sender_email' => PageContext::$response->sess_user_email,
                            'invitation_sender_id' => PageContext::$response->sess_user_id,
                            'invitation_receiver_email' => $list[$i],
                            'invitation_status' => 'P',
                            'mail_template' => 'community_join_invite'
                        );
                        $res = Connections::checkInvitationSentEmail(PageContext::$response->sess_user_id, $list[$i], 'C', $id);
                        //     			echopre1($res);
                        if ($res == 0) {
                            $community_name = Communities::getCommunity($id);
                            $community_owner = Communities::getCommunityAlias($community_name->data->community_alias);
                            $objInvitationsVo = Utils::arrayToObject($invitations);
                            $objInvitationRes = Connections::addInvitation($objInvitationsVo);

                            Logger::info($objInvitationRes);
                            if ($objInvitationRes->status != SUCCESS) {
                                $flag = 1;
                                $message = $objInvitationRes->message;
                            }
                            $replaceparams['EMAIL'] = $list[$i];
                            $replaceparams['INVITE_ID'] = $objInvitationRes->invitation_id;
                            $replaceparams['COMMUNITY'] = $community_name->data->community_name;
                            $replaceparams['NAME'] = PageContext::$response->sess_user_name;
                            $replaceparams['IMG_URL'] = USER_IMAGE_URL_DEFAULT;
                            $replaceparams['INVITE_TYPE'] = 'join-community';
                            $mailIds[$list[$i]] = '';
                            $mailidowner = array();
                            $mailidowner[$community_owner->data->user_email] = '';

                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'community_join_invite', $replaceparams);

                            $objMailer->sendMail($mailidowner, 'community_join_invite_moderator', $replaceparams);
                            $count++;
                        } else {
                            if ($notSendCount != 0) {
                                $notSendList = $notSendList . ", ";
                            }
                            $notSendList = $notSendList . $list[$i];
                            $notSendCount++;
                        }
                    }
                }
                Logger::info($mailIds);
                if ($flag == 0) {
                    if ($notSendCount > 0) {
                        $msg = "Mail already sent to " . $notSendList;
                    } else {
                        $msg = '';
                    }
                    Messages::setPageMessage(INVITATION_SEND_SUCCESS, 'success_div');
                    $result = Messages::getPageMessage();
                    $result = INVITATION_SEND_SUCCESS . " to $count person(s). $msg";
                    $class = 'success_div';
                } else { //========User invitation failed =======
                    Messages::setPageMessage(INVITATION_SEND_FALIURE, 'error_div');
                    $result = Messages::getPageMessage();
                    $result = INVITATION_SEND_FALIURE;
                    $class = 'error_div';
                }
            } else {
                $result = CONTACTS_NOT_SELECTED;
                $class = 'error_div';
            }

            $data = array("msg" => $result, "cls" => $class);
            echo json_encode($data);
        }
        exit;
    }

    public function logout() {
        User::setUserOnlineStatus(PageContext::$response->sess_user_id);        
       session_start();
//        session_destroy();
//        session_unset();
       $_SESSION = array(); // Destroy the variables.
       session_destroy(); // Destroy the session itself.
       //setcookie( session_name(), ", time()-300, '/', ", 0 ); 
        header("location:" . BASE_URL);
        exit;
    }

   
    public function commentbox($type = '', $id = '') {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        //===========================Login Form================================
        $arrFormParams = array('name' => 'frmComment', 'id' => 'frmComment', 'method' => 'post', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('comment_content' => array('type' => 'textarea', 'id' => 'comment_content', 'name' => 'comment_content', 'value' => PageContext::$request['comment_content'], 'size' => 10, 'placeholder' => 'Comment',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter comment')))),
            'entity_type' => array('type' => 'hidden', 'name' => 'entity_type', 'value' => $type, 'id' => 'entity_type'),
            'entity_id' => array('type' => 'hidden', 'name' => 'entity_id', 'value' => $id, 'id' => 'entity_id'),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Post', 'id' => 'loginbtn'),
        );

        $objFormManager->addFields($arrFormElements);
        PageContext::$response->type = $type;
        PageContext::$response->id = $id;
        PageContext::$response->objFormComment = $objFormManager->renderForm();
    }

    public function testimonialbox($id = '') {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        //===========================Testimonail Form================================
        $arrFormParams = array('name' => 'frmComment', 'id' => 'frmComment', 'method' => 'post', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array(
            'testimonial_content' => array('type' => 'textarea', 'id' => 'testimonial_content', 'name' => 'testimonial_content', 'value' => PageContext::$request['testimonial_content'], 'size' => 10, 'placeholder' => 'Your Testimonial',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter testimonial content')))),
            'entity_type' => array('type' => 'hidden', 'name' => 'entity_type', 'value' => $type, 'id' => 'entity_type'),
            'entity_id' => array('type' => 'hidden', 'name' => 'entity_id', 'value' => $id, 'id' => 'entity_id'),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Post', 'id' => 'loginbtn'),
        );

        $objFormManager->addFields($arrFormElements);
        PageContext::$response->type = $type;
        PageContext::$response->id = $id;
        PageContext::$response->objFormComment = $objFormManager->renderForm();
    }

    public function inqurebox($type = '', $id = '') {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        //===========================Login Form================================
        $arrFormParams = array('name' => 'frmComment', 'id' => 'frmComment', 'method' => 'post', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $username = (PageContext::$response->sess_user_name != '') ? PageContext::$response->sess_user_name : '';
        $arrFormElements = array('inquire_name' => array('type' => 'text', 'id' => 'inquire_name', 'name' => 'inquire_name', 'value' => $username, 'size' => 10, 'class' => '', 'placeholder' => 'Your Name',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter your Name')))),
            'from_email' => array('type' => 'text', 'id' => 'from_email', 'name' => 'from_email', 'value' => PageContext::$response->sess_user_email, 'size' => 10, 'placeholder' => 'Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'inquire_content' => array('type' => 'textarea', 'id' => 'inquire_content', 'name' => 'inquire_content', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Inquiry',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter message')))),
            'entity_type' => array('type' => 'hidden', 'name' => 'entity_type', 'value' => $type, 'id' => 'entity_type'),
            'entity_id' => array('type' => 'hidden', 'name' => 'entity_id', 'value' => $id, 'id' => 'entity_id'),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Send', 'id' => 'loginbtn'),
        );

        $objFormManager->addFields($arrFormElements);
        PageContext::$response->type = $type;
        PageContext::$response->id = $id;
        PageContext::$response->objFormComment = $objFormManager->renderForm();
    }

    public function addComment() {

        $objUserRes = new stdClass();
        $objCommentData = new stdClass();

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();


        $objUserRes->status = SUCCESS;
        if (isset(PageContext::$request['comment_content']) && PageContext::$request['comment_content'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Comment";
        }

        if ($objUserRes->status == SUCCESS) {

            $objCommentData->comment_content = PageContext::$request['comment_content'];
            $objCommentData->comment_created_on = date("Y-m-d H:i:s");
            $objCommentData->comment_created_by = Utils::getAuth('user_id');
            $objCommentData->comment_entity_type = PageContext::$request['entity_type'];
            $objCommentData->comment_entity_id = PageContext::$request['entity_id'];
            $objCommentData->comment_status = 'A';
            $objCommentData->comment_parent = 0;

            $objUserRes = Comments::createComment($objCommentData);
        }


        echo json_encode(Utils::objectToArray($objUserRes));
        exit;
    }

    public function add_testimonial() {
        $objUserRes = new stdClass();
        $objCommentData = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes->status = SUCCESS;
        if (isset($_POST['testimonialContent']) && $_POST['testimonialContent'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Testtimonial Content";
        }
        if ($objUserRes->status == SUCCESS) {
            $objCommentData->business_id = $_POST['business_id'];
            $objCommentData->testimonial_content = PageContext::$request['testimonialContent'];
            $objCommentData->tetimonial_date = date("Y-m-d H:i:s");
            $objCommentData->user_id = Utils::getAuth('user_id');
            $objCommentData->testimonial_status = 'A';
            
            $objUserRes = Comments::createTestimonial($objCommentData);
        }
        $user_data = User::getUserDetail($objCommentData->user_id);
        PageContext::$response->testimonial_content = $objCommentData->testimonial_content;
        PageContext::$response->testimonial_user = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
        PageContext::$response->testimonial_date = $objCommentData->tetimonial_date;
        PageContext::$response->user_image = $user_data->data->Image;
        PageContext::$response->user_alias = $user_data->data->user_alias;
        PageContext::$response->testimonial_id = $objUserRes->data->comment_id;
        
//        echo json_encode(Utils::objectToArray($objUserRes));
//        exit;
        
    }

    public function loginpopup($id = '', $type = '', $flag = '') {
        //===========================Login Form================================
        $arrFormParams = array('name' => 'frmLogin', 'id' => 'frmLogin', 'method' => 'post', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('user_email' => array('type' => 'text', 'id' => 'user_email', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'placeholder' => 'Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'user_password' => array('type' => 'password', 'id' => 'user_password', 'name' => 'user_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password'), 'minlength' => array('8', 'Please enter at least 8 characters'), 'passcheck' => array('8', 'Please enter a password with an uppercase character and a numeric.')))),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Log in', 'id' => 'loginbtn'),
        );
        $objFormManager->addFields($arrFormElements);
        PageContext::$response->objFormLogin = $objFormManager->renderForm();
        PageContext::$response->tflag = $id;
        PageContext::$response->flag = $flag;
        PageContext::$response->type = $type;

        //================ Registration Form =======================
        $arrFormParams1 = array('name' => 'frmUserRegister_sign', 'id' => 'frmUserRegister_sign', 'method' => 'post', 'class' => '');
        $objFormManager1 = new Formmanager($arrFormParams1);
        $arrFormElements1 = array(
            'user_email' => array('type' => 'text', 'id' => 'user_email_sign', 'name' => 'user_email_sign', 'value' => PageContext::$request['user_email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
                'label' => array('message' => '', 'class' => ''),
            ),
            'user_password' => array('type' => 'password', 'id' => 'user_password_sign', 'name' => 'user_password_sign', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password'), 'minlength' => array('8', 'Please enter at least 8 characters'), 'passcheck' => array('8', 'Please enter a password with an uppercase character and a numeric.')))),
            //),
            'user_confirm_password' => array('type' => 'password', 'id' => 'user_confirm_password_sign', 'name' => 'user_confirm_password_sign', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Re-enter Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please re-enter password'), 'confirm' => array('true', 'user_password_sign', 'Password mismatch!')))),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Sign Up For BizB Friend', 'id' => 'signbtn'),
        );
        $objFormManager1->addFields($arrFormElements1);
        PageContext::$response->objFormRegister = $objFormManager1->renderForm();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function ajaxLogin($tflag, $id, $flag) {
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        if (PageContext::$request['user_email'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Email";
        }
        if (PageContext::$request['user_password'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Password";
        }

        if (!filter_var(PageContext::$request['user_email'], FILTER_VALIDATE_EMAIL)) {

            $objUserRes->status = ERROR;
            $objUserRes->message = "Invalid Email Address";
        }

        $objUserVo = Utils::arrayToObject($_POST);
        $objUserRes = User::loginUser($objUserVo);
        $res = Business::getBusinessById($flag);
        // echo $res->data->business_created_by."**".$objUserRes->data->user_id;exit;
        if ($res->data->business_created_by == $objUserRes->data->user_id)
            $objUserRes->data->user_uid = 'Owner';
        else
            $objUserRes->data->user_uid = 0;
        $objUserRes->data->tflag = $id;
        if ($objUserRes->status == SUCCESS) {
            Utils::setSessions($objUserRes->data);
        }
        echo json_encode(Utils::objectToArray($objUserRes));
        exit;
    }

    public function ajaxRegister() {
        // echo "here";exit;
        $objUserRes = new stdClass();
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objUserRes->status = SUCCESS;
        $msg = '';
        //print_r($_POST);exit;
        if (PageContext::$request['user_email'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Email";
        }
        if (PageContext::$request['user_password'] == '') {
            $objUserRes->status = ERROR;
            $objUserRes->message = "Please Enter Password";
        }

        if (!filter_var(PageContext::$request['user_email'], FILTER_VALIDATE_EMAIL)) {

            $objUserRes->status = ERROR;
            $objUserRes->message = "Invalid Email Address";
        }

        if (PageContext::$request['user_password'] != PageContext::$request['user_confirm_password']) {

            $objUserRes->status = ERROR;
            $objUserRes->message = "Password Mismatch";
        }

        $unsetArray = array('btnSubmit', 'user_confirm_password');
        $additionalParameters = array(
            'user_password' => md5(PageContext::$request['user_password']),
            'user_created_on' => date('Y-m-d')
        );

        if ($objUserRes->status == SUCCESS) {
            $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
            if (ADMIN_APPROVE_USER_AUTO == 1) {
                $objUserVo->user_status = 'A';
                $msg = REGISTER_SUCCESS;
            } else {
                $objUserVo->user_status = 'I';
                //   $objUserVo->msg = REGISTER_SUCCESS.USER_NOT_ACTIVATED;
                $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
            }
            $objUserRes = User::createUser($objUserVo);
            $objUserVo->msg = $msg;
        }

        if ($objUserRes->status == SUCCESS) {//==========User Registration mail==========
            //echopre1($objUserRes);
            $mailIds = array();
            $replaceparams = array();
            $mailIds[PageContext::$request['user_email']] = '';
            $replaceparams['FIRST_NAME'] = '';
            //$replaceparams['LAST_NAME']                   = '';
            //$replaceparams['FIRST_NAME']                  = $objUserRes->data->user_firstname;
            $replaceparams['LAST_NAME'] = '';
            $replaceparams['LOGIN_NAME'] = PageContext::$request['user_email'];
            $replaceparams['PASSWORD'] = PageContext::$request['user_password'];
            $objMailer = new Mailer();
            $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);

            //Mail to admin
            $adminemail = Utils::getAdminMail();
            $mailIds1[$adminemail] = $adminemail;
            $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
            $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
            $replaceparams['USER_EMAIL'] = PageContext::$request['user_email'];
            $replaceparams['SITE_NAME'] = 'BizBFriend';
            $objMailer = new Mailer();
            $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
            // echopre1($objUserRes);
            //================== set session===================
            Utils::setSessions($objUserRes->data);
            //  echopre1($objUserRes);
        } else { //========== User insertion failed ==============
            //Messages::setPageMessage($objUserRes->message,'error_div');
        }
        //  echopre1($objUserRes);
        echo json_encode(Utils::objectToArray($objUserRes));
        exit;
    }

    /*
     * Right hand side profile search
     */

    public function searchprofile() {
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");

        PageContext::addScript('search.js');
        PageContext::$body_class = 'business_profile';
        PageContext::registerPostAction("leftcontent", "searchprofile", "index", "default");
        $searchText = PageContext::$request->searctext;
        $page = PageContext::$request['page'];
        $search = addslashes(PageContext::$request['searchtext']);
        $searchtypeArray = array('user_firstname', 'user_lastname');
        $searchtype = 'all';
        $itemperpage = PAGE_LIST_COUNT;
        if ($orderby == '')
            $orderby = ' ASC';
        if ($orderfield == '')
            $orderfield = 'user_firstname';
        PageContext::$response->searchtext = $search;
        PageContext::$response->searchtype = 'all';
        PageContext::$response->page = $page;
        PageContext::$response->messagebox = Messages::getPageMessage();
        PageContext::$response->order = ($orderby == 'DESC') ? 'ASC' : 'DESC';
        PageContext::$response->message = $messageArray['msg'];
        PageContext::$response->class = $messageArray['msgClass'];
        $targetpage = BASE_URL . 'index/searchprofile?searchtext=' . $search . '&searchtype=' . $searchtype . '&sort=' . $orderfield . '&sortby=' . $orderby;
        if ($search != "") {
            $users = User::getAllUsers($orderfield, $orderby, $page, $itemperpage, $search, $searchtypeArray);
        }
        PageContext::$response->usersList = $users->records;
//        PageContext::$response->business    = Business::getBusinessSearch($search);
//        PageContext::$response->community   = Communities::getCommunitySearch($search);
        if (PageContext::$response->sess_user_id != '') {
            $friends = User::getUserFriends(PageContext::$response->sess_user_alias, 'users.user_id');
            foreach ($friends->data AS $friends) {
                $myfriends[] = $friends->user_id;
            }
            PageContext::$response->myfriends = $myfriends;
            $invitations = Connections::getAllUserInvitationsSent(PageContext::$response->sess_user_alias, 'P', 'invitation_receiver_id');
            foreach ($invitations->data AS $invitations) {
                $myinvitations[] = $invitations->invitation_receiver_id;
            }
            PageContext::$response->myinvitedfriends = $myinvitations;
            $pendingFriendRequests = Connections::getUserPendingRequest(PageContext::$response->sess_user_alias);
            foreach ($pendingFriendRequests->data AS $pendingFriendRequest) {
                $myPendingRequests[] = $pendingFriendRequest->user_id;
                $myPendingRequestsInviteId[] = $pendingFriendRequest->invitation_id;
            }
//             echopre($myPendingRequests);
//             echopre($myPendingRequestsInviteId);
//             echopre($users->records);
            foreach ($users->records AS $k => $val) {
//             	echopre($val);
// 			$key = '';
                $key = array_search($val->user_id, $myPendingRequests);
//             echo $key;
                if ($myPendingRequests[$key] == $val->user_id) {
                    //  if($key >= 0){ //echo"aaa";
//             	$friendId = $myPendingRequests[$key];            	
                    $inviteId = $myPendingRequestsInviteId[$key];

                    //PageContext::$response->friendId = $friendId;
                    //echopre($inviteId);            
                    $users->records[$k]->inviteId = $inviteId;
                    //$key = '';
//             	echopre($val);
//             	PageContext::$response->inviteId = $inviteId;            	
                }
            }
//             echopre($users->records);
            PageContext::$response->usersList = $users->records;
            PageContext::$response->myPendingRequests = $myPendingRequests;
//             PageContext::$response->myPendingRequestsInviteId = $myPendingRequestsInviteId;
        }
        //echopre(PageContext::$response->usersList);
        if ($page > 1)
            PageContext::$response->slno = ((($itemperpage * $page ) - $itemperpage) + 1);
        else
            PageContext::$response->totalrecords = $users->totalrecords;
        PageContext::$response->pagination = Pagination::paginate($page, $itemperpage, $users->totalrecords, $targetpage);
    }

    public function profilechange($id) {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        PageContext::$response->file = '';
        PageContext::$response->id = $id;
        if (PageContext::$request['image_submit']) {
            $objUserRes = new stdClass();
            $objUserImageData = new stdClass();

            $objUserRes->status = SUCCESS;
            $div = 'success_div';
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] == '') {
                $objUserRes->status = ERROR;
                $objUserRes->message['msg'] = "Please Upload File";
                $div = 'error_div';
            }
            if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
                $type = $_FILES['file']['type'];
                $type1 = @explode('/', $type);
                if ($type1[0] != 'image' || !in_array($type1[1], array("gif", "jpeg", "jpg", "png"))) {
                    $objUserRes->status = ERROR;
                    $objUserRes->message['msg'] = "File format not supported.";
                    $div = 'error_div';
                }
            }
            if ($objUserRes->status == SUCCESS) {

                $objUserImageData->user_id = PageContext::$request['user_id'];
                $objUserImageData->file = $_FILES['file'];
                list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);

                $objUserRes->message = User::updateUserProfilePic($objUserImageData,$width,$height);
                $div = $objUserRes->message['msgcls'];
                PageContext::$response->file = $objUserRes->message['file'];
            }

            PageContext::$response->message['msg'] = $objUserRes->message['msg'];
            PageContext::$response->message['msgClass'] = $div;
            $_SESSION['default_user_image_name'] = $objUserRes->message['file'];
        }
    }

     public function addProfilePic($id)
     {
     	$objUserRes = new stdClass();
     	$objUserImageData = new stdClass();
     	PageContext::$full_layout_rendering 	= false;
     	$this->view->disableLayout();
         
     	$objUserRes->status = SUCCESS;
     	$div = 'success_div';
     	if(isset($_FILES['file']['name']) && $_FILES['file']['name'] == '' )
     	{
     		$objUserRes->status = ERROR;
     		$objUserRes->message = "Please Upload File";
     		$div = 'error_div';
     	}
     	if($objUserRes->status == SUCCESS)
     	{
     		$objUserImageData->user_id = $id;
     		$objUserImageData->file = $_FILES['file'];    	
                list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
     		$objUserRes->message = User::updateUserProfilePic($objUserImageData,$width, $height);
     		$div = $objUserRes->message['msgcls'];
     	}
         
        unset($_SESSION['default_user_image_name']);
        $_SESSION['default_user_image_name'] = '';
        $_SESSION['default_user_image_name']         = $objUserRes->message['file'];
        echo $objUserRes->message['file'];exit;
//     	PageContext::$response->message['msg'] = $objUserRes->message['msg'];
//     	PageContext::$response->message['msgClass'] = $div;
//     	echo $objUserRes->message['msg'];
//     	echo $div;
//     	exit;
     }

    public function addOrgProfilePic($id)
    {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $objOrgRes = new stdClass();
        $objOrgImageData = new stdClass();
        $objOrgRes->status = SUCCESS;
        $div = 'success_div';
        
        if(isset($_FILES['file']['name']) && $_FILES['file']['name'] == '' ) {
            $objOrgRes->status = ERROR;
            $objOrgRes->message = "Please Upload File";
            $div = 'error_div';
        }
        if($objOrgRes->status == SUCCESS) {
            $objOrgImageData->business_id = $id;
            $objOrgImageData->file = $_FILES['file'];
            list($width, $height, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
            $objOrgRes->message = Business::updateOrgProfilePic($objOrgImageData,$width, $height);
        }
        echo $objOrgRes->message['file'] ;
    }

    public function accept_invitation($id, $type, $flag = 1, $redirect = '') {
        // echo "dkjsdf".PageContext::$response->sess_user_id;exit;
        //PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");  
          if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header", "index", "default");
        }
        PageContext::registerPostAction("banner", "banner", "index", "default");
        PageContext::registerPostAction("leftcontent", "leftcontent", "index", "default");
        PageContext::registerPostAction("messagebox", "messagebox", "index", "default");	
        //PageContext::registerPostAction("leftcontent", "accept_invitation", "index", "default");

        PageContext::addScript('index.js');
        $msg = '';
        //$flag = 0;
        PageContext::$body_class = 'home';

        PageContext::$response->activeSubMenu = '';
        PageContext::$response->type = $type;
        PageContext::$response->id = $id;
        $invite = Connections::getInvitationDetails($id);
        // echopre1($invite);
        if ($invite->status == 'SUCCESS') {
            if ($invite->data->invitation_status != 'P') {
                Messages::setPageMessage(INVITATION_ACCEPTED, 'error_div');
                $this->redirect('#jmessage');
            } else {
                $inviteDetails1 = array('invitation_action_deffered' => '1');
                $inviteVo1 = Utils::arrayToObject($inviteDetails1);
                $inviteRes1 = Connections::changeInvitationStatus($id, $inviteVo1);
                if (PageContext::$response->sess_user_id > 0) {
                    if ($flag == 1) {
                        session_destroy();
                        session_unset($_SESSION['user']);
                        $this->redirect('accept-invitation/' . $id . '/' . $type . '/' . $flag);
                    }
                    //$objUserRes1      =   User::getUserDetails(PageContext::$response->sess_user_alias);
                    //$this->redirect('profile/'.PageContext::$response->sess_user_alias);
                }
                //echo PageContext::$response->sess_user_id;exit;
//     	else {    	
                if (PageContext::$response->sess_user_id == '') {
                    //echo "here";exit;
                    //===========================Login Form================================
                    $arrFormParams = array('name' => 'frmLogin', 'id' => 'frmLogin', 'method' => 'post', 'action' => BASE_URL . 'accept-invitation/' . $id . '/' . $type . '/' . $flag, 'class' => '');
                    $objFormManager = new Formmanager($arrFormParams);
                    $mail = (Utils::getCookies('user_email') != '') ? Utils::getCookies('user_email') : PageContext::$request['user_email'];
                    $password = (Utils::getCookies('user_password') != '') ? Utils::getCookies('user_password') : '';
                    $rememberCheck = (Utils::getCookies('user_email') != '') ? 'checked' : '';
                    //echopre($_COOKIE);
                    $arrFormElements = array(
                        'user_email' => array('type' => 'text', 'name' => 'user_email', 'value' => $mail, 'size' => 10, 'placeholder' => 'Email',
                            'label' => array('message' => '', 'class' => ''),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
                        'user_password' => array('type' => 'password', 'name' => 'user_password', 'value' => $password, 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                            'label' => array('message' => '', 'class' => ''),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password')))),
                        'remember_me' => array('type' => 'checkbox', 'name' => 'remember_me', 'value' => '1', 'size' => 10, 'class' => '', 'placeholder' => '', 'title' => 'Remember Me', $rememberCheck,
                            'label' => array('message' => '', 'class' => 'checkbox'),
                        ),
                        'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Sign In'),
                    );
                    $objFormManager->addFields($arrFormElements);
                    if (PageContext::$request['btnSubmit'] == 'Sign in') { //=======Post action==============
                        //echo "1";exit;
                        $objValidator = new formValidator();
                        $validation = $objValidator->validate($arrFormElements);

                        if ($validation['error'] == 1) {
                            $objFormManager->addValidationMessages($validation);
                        } else {
                            //echopre(PageContext::$request);
                            $objUserVo = Utils::arrayToObject($_POST);
                            $objUserRes = User::loginUser($objUserVo);
                            if ($objUserRes->status == 'SUCCESS') {
                                //echopre($objUserRes);
                                //=============Set Session =============
                                Utils::setSessions($objUserRes->data);
                                $this->redirect('pending-request');
                            } else {
                                Messages::setPageMessage($objUserRes->message, 'error_div');
                            }
                        }
                    }
                    PageContext::$response->message = Messages::getPageMessage();
                    PageContext::$response->objForm = $objFormManager->renderForm();

                    //================ Registration Form =======================
                    $title = "I agree to the <a href='" . BASE_URL . "terms' target='_blank'>Terms of Service</a> and <a href='" . BASE_URL . "privacy-policy' target='_blank'>Privacy Policy</a>.";
                    $arrFormParams = array('name' => 'frmUserRegister', 'id' => 'frmUserRegister', 'method' => 'post', 'action' => BASE_URL . 'accept-invitation/' . $id . '/' . $type . '/' . $flag, 'class' => '');
                    $objFormManager = new Formmanager($arrFormParams);
                    $arrFormElements = array(
                        'user_email' => array('type' => 'text', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
                            'label' => array('message' => '', 'class' => ''),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
                        'user_password' => array('type' => 'password', 'name' => 'user_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                            'label' => array('message' => '', 'class' => ''),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password')))),
                        'user_confirm_password' => array('type' => 'password', 'name' => 'user_confirm_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Re-enter Password',
                            'label' => array('message' => '', 'class' => ''),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please re-enter password'), 'confirm' => array('true', 'user_password', 'Password mismatch!')))),
                        'terms_conditions' => array('type' => 'checkbox', 'name' => 'terms_conditions', 'value' => '1', 'size' => 10, 'class' => '', 'placeholder' => '', 'title' => $title,
                            'label' => array('message' => '', 'class' => 'checkbox'),
                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please accept the terms and conditions.')))),
                        'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Sign Up For BizB Friend'),
                    );

                    $objFormManager->addFields($arrFormElements);

                    if (PageContext::$request['btnSubmit'] == 'Sign Up') { //=========Post action========
                        //echo "2";exit;
                        $objValidator = new formValidator();
                        $validation = $objValidator->validate($arrFormElements);

                        if ($validation['error'] == 1) {
                            $objFormManager->addValidationMessages($validation);
                        } else {
                            //echopre(PageContext::$request);
                            $unsetArray = array('btnSubmit', 'user_confirm_password', 'terms_conditions');
                            $additionalParameters = array(
                                'user_password' => md5(PageContext::$request['user_password']),
                                'user_created_on' => date('Y-m-d')
                            );
                            $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
                            if (ADMIN_APPROVE_USER_AUTO == 1) {
                                $objUserVo->user_status = 'A';
                                $msg = REGISTER_SUCCESS;
                            } else {
                                $objUserVo->user_status = 'I';
                                $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                            }
                            $objUserRes = User::createUser($objUserVo);
                            //echopre1($objUserRes);
                             $this->redirect('pending-request');
                            if ($objUserRes->status == SUCCESS) {//==========User Registration mail==========
                                 $this->redirect('pending-request');
                                $mailIds = array();
                                $replaceparams = array();
                                $mailIds[PageContext::$request['user_email']] = '';
                                $replaceparams['FIRST_NAME'] = $objUserRes->data->user_firstname;
                                $replaceparams['LAST_NAME'] = '';
                                $replaceparams['LOGIN_NAME'] = PageContext::$request['user_email'];
                                $replaceparams['PASSWORD'] = PageContext::$request['user_password'];
                                $objMailer = new Mailer();
                                $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);

                                //Mail to admin
                                $adminemail = Utils::getAdminMail();
                                $mailIds1[$adminemail] = '';
                                $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                                $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                                $replaceparams['USER_EMAIL'] = PageContext::$request['user_email'];
                                $replaceparams['SITE_NAME'] = 'BizBFriend';
                                $objMailer = new Mailer();
                                $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
                                echo "here";exit;
                                $this->redirect('pending-request');
                                Messages::setPageMessage($msg, 'success_div');
                                //================== set session===================
                                Utils::setSessions($objUserRes->data);
                                //$this->redirect('profile/'.$objUserRes->data->user_alias);
                            } else { //========== User insertion failed ==============
                                 $this->redirect('pending-request');
                                Messages::setPageMessage($objUserRes->message, 'error_div');
                            }
                        }
                    }
//     	PageContext::$response->regestrationMessage      = Messages::getPageMessage();
                    PageContext::$response->objRegistrationForm = $objFormManager->renderForm();
                }
                PageContext::$response->regestrationMessage = Messages::getPageMessage();
//     	PageContext::$response->objRegistrationForm      = $objFormManager->renderForm();
                $alias = Utils::getAuth('user_id');
                PageContext::$response->sess_user_id = $alias;
                PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
                PageContext::$response->sess_user_email = Utils::getAuth('user_email');
                if ($type == 'reject') {

                    $inviteDetails = array('invitation_status' => 'R',
                        'invitation_action_deffered' => '0'
                    );
                    $inviteVo = Utils::arrayToObject($inviteDetails);
                    $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                    //echopre($inviteRes);
                    $invite = Connections::getInvitationDetails($id);
                    $sender = User::getUserDetail($invite->data->invitation_sender_id);
                    //echopre($friendsRes);
                    Messages::setPageMessage('You have rejected the request', 'success_div');
                    //	Messages::setPageMessage(REJECT_SUCCESS.$sender->data->Name,'success_div');
                }
                $userstatus = Utils::getAuth('user_status');
                if ($alias > 0) {
                    $msg = '';
//    		$path = 'profile/';
//    		if(ADMIN_APPROVE_USER_AUTO == 1){
//                   
//    			//$objUserVo->user_status ='A';
//    			$msg = REGISTER_SUCCESS;
//    			$path = 'profile/';
//    		}
//    		else{
//    			//$objUserVo->user_status ='I';
//    			$msg = REGISTER_SUCCESS.' '.USER_NOT_ACTIVATED;
//    			$path = 'inactiveuser';
//    		}
//            if($userstatus == 'A'){
//                      $path = 'profile/';
//             }
//            else if($userstatus == 'I'){
//                    $path = 'inactiveuser';
//                }
                    if ($type == 'friend') {
                        //echopre($objUserRes);
                        $inviteDetails = array('invitation_status' => 'A',
                            'invitation_action_deffered' => '0');
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                        //echopre($inviteRes);
                        $invite = Connections::getInvitationDetails($id);
                        //echopre1($invite);
                        $sender = User::getUserDetail($invite->data->invitation_sender_id);
                        //echopre($sender);
                        $friend = array('friends_list_user_id' => $invite->data->invitation_receiver_id,
                            'friends_list_friend_id' => $invite->data->invitation_sender_id
                        );
                        $friendVo = Utils::arrayToObject($friend);
                        $friendsRes = Connections::acceptFriendRequest($id, $friendVo);
                        User::updateUserFriendCount($invite->data->invitation_receiver_id);
                        User::updateUserFriendCount($invite->data->invitation_sender_id);
                        //echopre($friendsRes);
                        Messages::setPageMessage('Friend request accepted', 'success_div');
                        //Messages::setPageMessage($sender->data->Name.FRIEND_SUCCESS,'success_div');
                        //exit;
                    } elseif ($type == 'community') {
                        $inviteDetails = array('invitation_status' => 'A',
                            'invitation_action_deffered' => '0');
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                        //echopre($inviteRes);    			
                        $invite = Connections::getInvitationDetails($id);
                        $check = Communities::chekMemeber($invite->data->invitation_receiver_id, $invite->data->invitation_entity_id);
                        if ($check->status == "SUCCESS") {
                            Messages::setPageMessage("Already joined the group");
                        } else {
                            $sender = User::getUserDetail($invite->data->invitation_sender_id);
                            //echopre($invite);
                            $community = Communities::getCommunity($invite->data->invitation_entity_id);
                            if ($community->data->community_type == 'PRIVATE') {
                                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                                    'cmember_community_id' => $invite->data->invitation_entity_id,
                                    'cmember_type' => 'U',
                                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                    //  'cmember_created_by'    => $invite->data->invitation_sender_id,
                                    'cmember_status' => 'A'
                                );
                                Messages::setPageMessage(COMMUNITY_SUCCESS1 . ' ' . COMMUNITY_SUCCESS_APPROVAL, 'success_div');
                                //	Messages::setPageMessage(COMMUNITY_SUCCESS1.$community->data->community_name.COMMUNITY_SUCCESS_APPROVAL,'success_div');
                            } else {
                                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                                    'cmember_community_id' => $invite->data->invitation_entity_id,
                                    'cmember_type' => 'U',
                                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                    //	'cmember_created_by'    => $invite->data->invitation_sender_id,
                                    'cmember_status' => 'A'
                                );
                                Messages::setPageMessage(COMMUNITY_SUCCESS1, 'success_div');
                                //Messages::setPageMessage(COMMUNITY_SUCCESS1.$community->data->community_name,'success_div');
                            }
                            $memberVo = Utils::arrayToObject($member);
                            //$memberRes = Connections::acceptCommunityRequest($id,$memberVo);
                            $memberRes = Communities::addMembertoCommunity($memberVo);
                            Communities::updateCommunityCounts($invite->data->invitation_receiver_id);
                            //User::updateUserCount('user_community_count',  PageContext::$response->sess_user_id);
                            //echopre($memberRes);
                            Communities::updateCommunityCounts();
                        }
                    } elseif ($type == 'join-community') {
                        $inviteDetails = array('invitation_receiver_id' => PageContext::$response->sess_user_id,
                            'invitation_receiver_email' => PageContext::$response->sess_user_email,
                            'invitation_status' => 'A',
                            'invitation_action_deffered' => '0'
                        );
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                        //echopre($inviteRes);
                        $invite = Connections::getInvitationDetails($id);
                        $check = Communities::chekMemeber($invite->data->invitation_receiver_id, $invite->data->invitation_entity_id);
                        if ($check->status == "SUCCESS") {
                            Messages::setPageMessage("Already joined the group");
                        } else {
                            $sender = User::getUserDetail($invite->data->invitation_sender_id);
                            //echopre($invite);
                            $community = Communities::getCommunity($invite->data->invitation_entity_id);
                            if ($community->data->community_type == 'PRIVATE') {
                                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                                    'cmember_community_id' => $invite->data->invitation_entity_id,
                                    'cmember_type' => 'U',
                                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                    //  'cmember_created_by'    => $invite->data->invitation_sender_id,
                                    'cmember_status' => 'A'
                                );
                                Messages::setPageMessage($msg . ' ' . COMMUNITY_SUCCESS1 . ' ' . COMMUNITY_SUCCESS_APPROVAL, 'success_div');
                                //Messages::setPageMessage(REGISTER_SUCCESS.COMMUNITY_SUCCESS1.$community->data->community_name.COMMUNITY_SUCCESS_APPROVAL,'success_div');
                            } else {
                                //echo $PageContext::$response->sess_user_id;
                                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                                    'cmember_community_id' => $invite->data->invitation_entity_id,
                                    'cmember_type' => 'U',
                                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                    //	'cmember_created_by'    => $invite->data->invitation_sender_id,
                                    'cmember_status' => 'A'
                                );
                                Messages::setPageMessage(REGISTER_SUCCESS . ' ' . COMMUNITY_SUCCESS1, 'success_div');
//     				Messages::setPageMessage(REGISTER_SUCCESS.COMMUNITY_SUCCESS1.$community->data->community_name,'success_div');
                            }
                            $memberVo = Utils::arrayToObject($member);
                            //$memberRes = Connections::acceptCommunityRequest($id,$memberVo);
                            $memberRes = Communities::addMembertoCommunity($memberVo);
                            Communities::updateCommunityCounts(PageContext::$response->sess_user_id);
                            //User::updateUserCount('user_community_count',  PageContext::$response->sess_user_id);
                            //echopre($memberRes);
                        }
                    } elseif ($type == 'join') {
                        //echopre($objUserRes);
                        $inviteDetails = array('invitation_receiver_id' => PageContext::$response->sess_user_id,
                            'invitation_receiver_email' => PageContext::$response->sess_user_email,
                            'invitation_status' => 'A',
                            'invitation_action_deffered' => '0'
                        );
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                        //echopre($inviteRes);
                        $invite = Connections::getInvitationDetails($id);
                        $sender = User::getUserDetail($invite->data->invitation_sender_id);
                        $friend = array('friends_list_user_id' => $invite->data->invitation_receiver_id,
                            'friends_list_friend_id' => $invite->data->invitation_sender_id
                        );
                        $friendVo = Utils::arrayToObject($friend);
                        $friendsRes = Connections::acceptFriendRequest($id, $friendVo);
                        //echopre($friendsRes);
                        User::updateUserFriendCount(PageContext::$response->sess_user_id);
                        User::updateUserFriendCount($invite->data->invitation_sender_id);
                        Messages::setPageMessage($msg . ' Friend request accepted.', 'success_div');
                        //Messages::setPageMessage(REGISTER_SUCCESS.$sender->data->Name.FRIEND_SUCCESS,'success_div');
                    }
                    if ($type == 'reject') {
                        $inviteDetails = array('invitation_status' => 'R',
                            'invitation_action_deffered' => '0'
                        );
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
                        //echopre($inviteRes);
                        $invite = Connections::getInvitationDetails($id);
                        $sender = User::getUserDetail($invite->data->invitation_sender_id);
                        //echopre($friendsRes);
                        Messages::setPageMessage('You have rejected the request', 'success_div');
                        //	Messages::setPageMessage(REJECT_SUCCESS.$sender->data->Name,'success_div');
                    }
                    //PageContext::$response->messagebox      = Messages::getPageMessage();

                    if ($redirect == '') {
                        if ($path == 'profile/') {
                            //if(ADMIN_APPROVE_USER_AUTO == 1){
                            $this->redirect($path . PageContext::$response->sess_user_alias);
                        } else {
                            $this->redirect($path);
                        }
                    } else {
                        $this->redirect($redirect);
                    }
                }
            }
        } else {
            Messages::setPageMessage($invite->message, 'error_div');
            $this->redirect('');
        }
        //PageContext::$response->messagebox      = Messages::getPageMessage();
//     	PageContext::$response->objRegistrationForm      = $objFormManager->renderForm();
    }

    public function joingroup() {
        // echo "here";exit;
        if ($_GET['type']) {
            $communityId = $_GET['community_id'];
            $type = $_GET['type'];
        } else {
            $communityId = PageContext::$request['community_id'];
            $type = PageContext::$request['type'];
        }
        $objMemvo = new stdClass();
        // echo $type;exit;
        if ($type == 'join' || $type == 'refer') {
            $check = Communities::chekMemeber(Utils::getAuth('user_id'), $communityId);
           // echopre1($check);
            if ($check->status != "SUCCESS") {
                $communityDetail = Communities::getCommunity($communityId);
                $communityDetail = $communityDetail->data;
                $objMemvo->cmember_id = Utils::getAuth('user_id');
                $objMemvo->cmember_community_id = $communityId;
                $objMemvo->cmember_type = 'U';
                $objMemvo->cmember_joined_on = date('Y-m-d H:i:s');
                $objMemvo->cmember_status = ($communityDetail->community_type == 'PUBLIC') ? 'A' : 'I';

                $result = Communities::addMembertoCommunity($objMemvo);
                $result->status = "SUCCESS";
                $result->message = "Successfully joined to the group";
                if ($communityDetail->community_type == 'PUBLIC') {
                    $result->message = 'You are now a member of ' . $communityDetail->community_name . '...';
                } else {
                    $result->message = $communityDetail->community_name . ' Admin will Verify Your Request!';
                }
            } else {
                $result->status = "SUCCESS";
                $result->message = "Already a member of the group";
            }
            Messages::setPageMessage($result->message, 'success_div');
            //echopre1($result);
            echo json_encode(Utils::objectToArray($result));
            exit;
        } else {
            $communityDetail = Communities::getCommunity($communityId);
            $communityDetail = $communityDetail->data;
            $objMemvo->cmember_id = Utils::getAuth('user_id');
            $objMemvo->cmember_community_id = $communityId;
            $objMemvo->cmember_status = 'D';
            $result = Communities::deleteMemeberCommunityStatus($objMemvo);
            $res = Connections::rejectStatus($objMemvo->cmember_id, $communityId, 'C');
            $result->message = COMMUNITY_MEMBER_UNJOIN;
            Messages::setPageMessage($result->message, 'success_div');
            echo json_encode(Utils::objectToArray($result));
            exit;
        }
        Communities::updateCommunityCounts();
        PageContext::$response->message = Messages::getPageMessage();
    }

    public function joinmail() {

        $communityId = PageContext::$request['community_id'];
        // $type                           = PageContext::$request['type'];
        // $objMemvo                       = new stdClass();
        //$check                          = Communities::chekMemeber(Utils::getAuth('user_id'), $communityId);
        $community_name = Communities::getCommunity($communityId);
        $community_owner = Communities::getCommunityAliasname($community_name->data->community_alias);
        $objMemvo = new stdClass();
        $objMemvo->cmember_id = Utils::getAuth('user_id');
        $objMemvo->cmember_community_id = $communityId;
        $objMemvo->cmember_type = 'U';
        $objMemvo->cmember_joined_on = date('Y-m-d H:i:s', strtotime('now'));
        $objMemvo->cmember_status = 'P';
        $objMemvo->cmember_pif_id = 0;
        $objMemvo->cmember_campaign_id = 0;
        // echopre($objMemvo);exit;
        Communities::addMembertoCommunity($objMemvo,$community_owner->data->community_created_by);
                                $mailIds = array();
                                $mailIds[$community_owner->data->user_email] = '';
                                $replaceparams['USER_NAME']                     = PageContext::$response->sess_user_name;
                                if($community_owner->data->user_firstname != ''){
                                $replaceparams['FIRST_NAME']                    = $community_owner->data->user_firstname;
                                $replaceparams['LAST_NAME']                     = $community_owner->data->user_lastname;
                                }else{
                                $replaceparams['FIRST_NAME']                    = $community_owner->data->user_email;
                                $replaceparams['LAST_NAME']                     = '';    
                                }
                                $replaceparams['COMMUNITY_NAME']                = $community_owner->data->community_name;
                                $replaceparams['SITE_NAME']                     = 'BizBFriend';
                                $objMailer                                      = new Mailer();
                                $objMailer->sendMail($mailIds, 'join_private_community ', $replaceparams);
        
        $message_detail = 'You have got a join request from a user named '.Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname').' in your  ' . $community_owner->data->community_name;
        $message_to_id = $community_owner->data->community_created_by;
        $message_from_id = Utils::getAuth('user_id');
        $message_date = date('Y-m-d', time());
        $message_subject = 'Join Request';

        Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);
        $msg->message = 'Your request sent to the owner of the group successfully...';
        Messages::setPageMessage($msg, 'success_div');
//        if($check->status != "SUCCESS"){
//        $communityDetail                = Communities::getCommunity($communityId); 
//        $communityDetail                = $communityDetail->data;
//        $objMemvo->cmember_id           = Utils::getAuth('user_id');
//        $objMemvo->cmember_community_id = $communityId;
//        $objMemvo->cmember_type         = 'U';
//        $objMemvo->cmember_joined_on    = date('Y-m-d H:i:s');
//        $objMemvo->cmember_status       = ($communityDetail->community_type=='PUBLIC')?'A':'I';
//        
//        $result                         = Communities::addMembertoCommunity($objMemvo);
//        if($communityDetail->community_type=='PUBLIC')
//        {
//            $result->message            = COMMUNITY_MEMBER;
//        }else{
//            $result->message            = COMMUNITY_MEMBER_PRIVATE;
//        }
//        }
//        else{
//        	$result->status         = "SUCCESS";
//        	$result->message        = "Already a member of the community";
//        }
//        echo json_encode(Utils::objectToArray($result));
//        exit;
        Communities::updateCommunityCounts();
        PageContext::$response->message = Messages::getPageMessage();
        echo json_encode(Utils::objectToArray($msg));
        exit;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function acceptgroup() {

        $communityId = PageContext::$request['community_id'];
        $type = PageContext::$request['type'];
        $userId = PageContext::$request['userId'];
        $objMemvo = new stdClass();
        if ($type == 'accept') {
            $objMemvo->cmember_status = 'A';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::chanegeMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_ACCEPT;
            echo json_encode(Utils::objectToArray($result));
            exit;
        } else {

            $objMemvo->cmember_status = 'D';
            $objMemvo->cmember_id = $userId;
            $objMemvo->cmember_community_id = $communityId;
            $result = Communities::deleteMemeberCommunityStatus($objMemvo);
            $result->message = COMMUNITY_REQ_DECLINE;
            echo json_encode(Utils::objectToArray($result));
            exit;
        }


        Communities::updateCommunityCounts();
    }

    public function invitetogroup($communityId, $userId) {

        $objUserRes = new stdClass();

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $getMembers = Communities::getFriendList($communityId, $userId);
//      echopre($getMembers);
        PageContext::$response->members = $getMembers->data;
        PageContext::$response->communityId = $communityId;
        PageContext::$response->userId = $userId;
    }

    public function rate($location = '', $id = '') {
        //PageContext::addScript("jquery.rateit.js");
        //PageContext::addScript("rating.js");
        PageContext::addStyle("rateit.css");

        $type = PageContext::$response->rate_entity;
        $type_alias = PageContext::$response->rate_entity_alias;
        if ($type == 'B') {
            $result = Business::getBusinessId($type_alias);
            $type_id = $result->data->business_id;
            $results = Business::getBusinessOwnerCCStatus($type_id);
            $created_id = $results->data['business_created_by'];
        } else if ($type == 'C') {
            $result = Communities::getCommunityId($type_alias);
            $type_id = $result->data->community_id;
        }
        $user_id = PageContext::$response->sess_user_id;
        $value = 0;
        $flag = 0;
        $rate = Ratings::getRatings($type_id, $type);
        //echopre($rate);
        if ($rate->data->count != 0) {
            $value = $rate->data->total / $rate->data->count;
        }
        if ($user_id <= 0) {
            $flag = 1;
        } else {
            $rate1 = Ratings::checkIfRated($type_id, $type, $user_id);
            //echopre($rate1);
            if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
                $flag = 1;
            }
        }
        PageContext::addJsVar('RATEVALUE', $value);
        PageContext::addJsVar('RATEFLAG', $flag);
        PageContext::addJsVar('RATETYPE_ID', $type_id);
        PageContext::addJsVar('RATETYPE', $type);
        PageContext::addJsVar('RATE_USERID', $user_id);
        // end rating part
        PageContext::addScript("jquery.rateit.js");
        PageContext::addScript("rating.js");
        //	echo json_encode(Utils::objectToArray($result));
        //	exit;
    }

    public function rateit() {

        if($_REQUEST['id'] == ''){
            $id = Utils::getAuth('user_id');
        }
        else{
           $id  =  $_REQUEST['id'];
        }
        $rating = array('rating_value' => $_REQUEST['value'],
            'rating_entity' => $_REQUEST['type'],
            'rating_entity_id' => $_REQUEST['typeid'],
            //  'comment_created_by'  =>  $objRatingsVo->comment_created_by,
            'rating_rated_by' => $id,
            'rating_rated_on' => date('Y-m-d H:i:s', strtotime('now')),
            'rating_status' => 'A'
        );
        $ratingVo = Utils::arrayToObject($rating);
        $rateRes = Ratings::addRatings($ratingVo);
        $newRate = Ratings::getRatings($_REQUEST['typeid'], $_REQUEST['type']);
        //if ($newRate->status == SUCCESS) {
        $rateValue = $newRate->data->total / $newRate->data->count;
        //}

        echo $rateValue;
        exit;
    }

    public function ratecheck() {
        $flag = 0;
        //echopre1($_REQUEST);
        if($_REQUEST['id'] == ''){
           $id = Utils::getAuth('user_id');
        }
        else{
            $id = $_REQUEST['id'];
        }
        $rate1 = Ratings::checkIfRated($_REQUEST['typeid'], $_REQUEST['type'], $id);
        // echopre($rate1) ;
        if ($rate1->data->rating_id > 0 || $rate1->data->rating_id != '') {
            $flag = 1;
        }
        if ($rate1->message == "You can't rate your own group") {
            $flag = 2;
        }
        if ($rate1->message == "You can't rate your own page") {
            $flag = 3;
        }
        if (is_array($rate1)) {
            if ($rate1[0]->rating_id > 0 && $rate1[0]->count > 0) {
                $flag = 4;
            }
        }
        if ($rate1->message == "You are not a member of this group") {
            $flag = 5;
        }

        echo $flag;
        exit;
    }

    public function profileautocomplete() {
        $result = User::getUserProfileName($_REQUEST['term']);


        $business = Business::getBusinessSearch($_REQUEST['term']);



        $community = Communities::getCommunitySearch($_REQUEST['term']);
        // echopre1($business);

        $data = array();

        foreach ($result as $k => $v) {
            $data[] = Utils::objectToArray($v);
        }

        if ($business) {
            foreach ($business as $k => $v) {
                $data[] = Utils::objectToArray($v);
            }
        }

        if ($community) {
            foreach ($community as $k => $v) {
                $data[] = Utils::objectToArray($v);
            }
        }

        echo json_encode($data);
        exit;
    }

    public function searchbusiness() {


        $business = Business::getBusinessSearchAll($_REQUEST['term']);




        // echopre1($business);



        if ($business) {
            foreach ($business as $k => $v) {
                $data[] = Utils::objectToArray($v);
            }
        }




        echo json_encode($data);
        exit;
    }

    public function searchdesignation() {
        $data = Business::getDesignationSearchAll($_REQUEST['term']);
        echo json_encode($data);
        exit;
    }

    public function sendCommunityInviatation() {
        $objUserRes = new stdClass();
        $objInviteData = new stdClass();

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();


        $objMailer = new Mailer();

        $sendUserDetails = User::getUserDetail(PageContext::$request['userId']);

        $sendUserDetails = $sendUserDetails->data;

        $communitDetails = Communities::getCommunity(PageContext::$request['communityId']);
        $communitDetails = $communitDetails->data;


        if (isset(PageContext::$request['senderId']) && PageContext::$request['senderId'] != '') {


            $getUserData = User::getUserDetail(PageContext::$request['senderId']);

            $getUserData = $getUserData->data;

            $objInviteData->invitation_type = 'E';
            $objInviteData->invitation_entity = 'C';
            $objInviteData->invitation_entity_id = PageContext::$request['communityId'];
            $objInviteData->invitation_sender_email = $sendUserDetails->Email;
            $objInviteData->invitation_sender_id = $sendUserDetails->Id;
            $objInviteData->invitation_receiver_id = $getUserData->Id;
            $objInviteData->invitation_receiver_email = $getUserData->Email;
            $objInviteData->invitation_status = 'P';
            $objInviteData->mail_template = 'invite';

            $result = Connections::addInvitation($objInviteData);
            // echopre1($result);

            if ($result->status == SUCCESS) {
                $mailIds = array();
                $replaceparams = array();
                $mailIds[$getUserData->Email] = ($getUserData->user_firstname) ? user_firstname : $getUserData->Email;
                $replaceparams['USER_NAME'] = ($getUserData->user_firstname) ? $getUserData->user_firstname : $getUserData->Email;
                $replaceparams['COMMUNITY'] = $communitDetails->community_name;
                $replaceparams['NAME'] = ($sendUserDetails->user_firstname) ? $sendUserDetails->user_firstname : $sendUserDetails->Email;
                $replaceparams['INVITE_ID'] = $result->invitation_id;
                $replaceparams['INVITE_TYPE'] = 'community';


                $objMailer->sendMail($mailIds, 'community_invite', $replaceparams);
            }





            if ($result->status == SUCCESS) {
                $objUserRes->status = SUCCESS;

                // Messages::setPageMessage(COMMUNITY_INVITE_SUCCESS, SUCCESS_CLASS);
            }

            echo json_encode($objUserRes);
            exit;
        }
    }

    public function delete_community($id) {
        $result = Communities::updateStatusDelete($id);
        if ($result->status == SUCCESS) {
            Messages::setPageMessage(COMMUNITY_DELETED, SUCCESS_CLASS);
            $this->redirect("my-groups");
        } else {
            Messages::setPageMessage(COMMUNITY_DELETED_FAIL, ERROR_CLASS);
            $this->redirect("my-groups");
        }

        Communities::updateCommunityCounts();
    }

    public function delete_organization($id) {
        $result = Business::updateStatusDelete($id);
        if ($result->status == SUCCESS) {
            Messages::setPageMessage(BUSINESS_DELETED, SUCCESS_CLASS);
            Business::updatebusinessCount();
            $this->redirect("pages");
        } else {
            Messages::setPageMessage(BUSINESS_DELETED_FAIL, ERROR_CLASS);
            $this->redirect("pages");
        }
    }

    public function inactiveuser() {
        PageContext::registerPostAction("leftcontent", "inactiveuser", "index", "default");
        PageContext::registerPostAction("messagebox", "messagebox", "index", "default");
        Utils::checkUserLoginStatus();
        if (PageContext::$response->sess_user_status != 'I') {
            Utils::redirecttohome();
        }
        //echopre1($_SESSION);	
        PageContext::$response->messagebox = Messages::getPageMessage();
        //echopre(PageContext::$response->messagebox);
    }

    public function error() {
        PageContext::$response->image_main_url=IMAGE_MAIN_URL;
        PageContext::$body_class = 'register';
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        }

        //PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");
        PageContext::registerPostAction("leftcontent", "error", "index", "default");
    }

    public function delete_comment($id) {
        $commentStatus = new stdClass();
        $commentStatus->comment_status = 'D';
//     	echopre($_SERVER);
//     	echo $_SERVER['HTTP_REFERER'];
        $path = str_replace(PageContext::$response->baseUrl, '', $_SERVER['HTTP_REFERER']);
//     	echo $path;exit;
        $result = Comments::changeCommentStatus($id, $commentStatus);
//     	$result = Business::updateStatusDelete($id);
        if ($result->status == SUCCESS) {
            Messages::setPageMessage(COMMENT_DELETED, SUCCESS_CLASS);
            $this->redirect($path);
        } else {
            Messages::setPageMessage(COMMENT_DELETED_FAIL, ERROR_CLASS);
            $this->redirect($path);
        }
    }

    public function delete_testimonial($id) {
        $commentStatus = new stdClass();
        $commentStatus->testimonial_status = 'D';
//     	echopre($_SERVER);
//     	echo $_SERVER['HTTP_REFERER'];
        $path = str_replace(PageContext::$response->baseUrl, '', $_SERVER['HTTP_REFERER']);
//     	echo $path;exit;
        $result = Comments::changeTestimonialStatus($id, $commentStatus);
//     	$result = Business::updateStatusDelete($id);
        if ($result->status == SUCCESS) {
         //   Messages::setPageMessage(TESTIMONIAL_DELETED, SUCCESS_CLASS);
           // $this->redirect($path);
        } else {
          //  Messages::setPageMessage(TESTIMONIAL_DELETED_FAIL, ERROR_CLASS);
           // $this->redirect($path);
        }
       echo json_encode($result);
        exit;
    }

    public function savecommentedit() {
        $id = $_POST["id"];
        $comment = $_POST["content"];
        $commentStatus = new stdClass();
        $commentStatus->comment_content = $comment;
        $result = Comments::editComment($id, $commentStatus);
        echo $result->data->comment_content;
        exit;
    }

    public function savetestimonialedit() {
        $id = $_POST["id"];
        $testimonial = $_POST["content"];
        $testimonialStatus = new stdClass();
        $testimonialStatus->testimonial_content = trim($testimonial);
        $result = Comments::editTestimonial($id, $testimonialStatus);
        echo $result->data->testimonial_content;
        exit;
    }

    public function addtag() {
        // echo "djkfkdjg";exit;
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        $objTag = Utils::arrayToObject($_POST, array('user_id' => Utils::getAuth('user_id')));
        $result = Business::addTagg($objTag);
        //echopre1($result);
        if ($result->tagg_id) {
            $getData = User::getAssociatedBusinessRow($result->tagg_id);
            // $result->data = $getData;
            PageContext::$response->tagDetails = $getData->data;
            // $this->redirect('myprofile');
            // header("location:" . BASE_URL."myprofile");
            echo json_encode($result->tagg_id);
            exit;
        } else {
            echo json_encode($result->tagg_id);
            exit;
        }
    }

    public function removetag() {
        if ($_POST['tagg_id']) {
            $getData = Business::removeTag($_POST['tagg_id']);
            echo json_encode($getData);
            exit;
        }
    }

    public function loginpoprate($type = '', $flag = '', $rateField = '') {
        // PageContext::addScript("validations_form.js");
        //===========================Login Form================================
        $arrFormParams = array('name' => 'frmLogin_rate', 'id' => 'frmLogin_rate', 'method' => 'post', 'class' => '');
        $objFormManager = new Formmanager($arrFormParams);
        $arrFormElements = array('user_email' => array('type' => 'text', 'id' => 'user_email', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'placeholder' => 'Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            'user_password' => array('type' => 'password', 'id' => 'user_password', 'name' => 'user_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password')))),
            'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Log in', 'id' => 'loginbtn'),
        );
        $objFormManager->addFields($arrFormElements);

        PageContext::$response->objFormLogin = $objFormManager->renderForm();

        PageContext::$response->flag = $flag;
        PageContext::$response->rateField = $rateField;
        PageContext::$response->type = $type;

        //================ Registration Form =======================
        $arrFormParams1 = array('name' => 'frmUserRegister_rate', 'id' => 'frmUserRegister_rate', 'method' => 'post', 'class' => '');
        $objFormManager1 = new Formmanager($arrFormParams1);
        $arrFormElements1 = array(
            'user_email' => array('type' => 'text', 'id' => 'user_email_rate', 'name' => 'user_email_rate', 'value' => PageContext::$request['user_email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
            //),
            'user_password' => array('type' => 'password', 'id' => 'user_password_rate', 'name' => 'user_password_rate', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password'), 'minlength' => array('8', 'Please enter at least 8 characters'), 'passcheck' => array('8', 'Please enter a password with an uppercase character and a numeric.')))),
            //),
            'user_confirm_password' => array('type' => 'password', 'id' => 'user_confirm_password_rate', 'name' => 'user_confirm_password_rate', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Re-enter Password',
                'label' => array('message' => '', 'class' => ''),
                'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please re-enter password'), 'confirm' => array('true', 'user_password_rate', 'Password mismatch!')))),
            //),
            'btnSubmit_rate' => array('type' => 'submit', 'name' => 'btnSubmit_rate', 'class' => 'yellow_btn', 'value' => 'Sign Up For BizB Friend', 'id' => 'signbtn'),
        );

        $objFormManager1->addFields($arrFormElements1);
        PageContext::$response->objFormRegister = $objFormManager1->renderForm();

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
    }

    public function accept_group_invite($id) {
        $result = new stdClass();
        $inviteDetails = array('invitation_status' => 'A',
            'invitation_action_deffered' => '0');
        $inviteVo = Utils::arrayToObject($inviteDetails);
        $inviteRes = Connections::changeInvitationStatus($id, $inviteVo);
        //echopre($inviteRes);
        $invite = Connections::getInvitationDetails($id);
        $check = Communities::chekMemeber($invite->data->invitation_receiver_id, $invite->data->invitation_entity_id);
        if ($check->status == "SUCCESS") {
            $result->status = "SUCCESS";
            $result->message = "Already joined the group";
//     		Messages::setPageMessage("Already joined the community");
        } else {
            $sender = User::getUserDetail($invite->data->invitation_sender_id);
            //echopre($invite);
            $community = Communities::getCommunity($invite->data->invitation_entity_id);
            if ($community->data->community_type == 'PRIVATE') {
                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                    'cmember_community_id' => $invite->data->invitation_entity_id,
                    'cmember_type' => 'U',
                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                    //  'cmember_created_by'    => $invite->data->invitation_sender_id,
                    'cmember_status' => 'A'
                );
                $result->status = "SUCCESS";
                $result->message = COMMUNITY_SUCCESS1 . ' ' . COMMUNITY_SUCCESS_APPROVAL;
                //Messages::setPageMessage(COMMUNITY_SUCCESS1.COMMUNITY_SUCCESS_APPROVAL,'success_div');
                //	Messages::setPageMessage(COMMUNITY_SUCCESS1.$community->data->community_name.COMMUNITY_SUCCESS_APPROVAL,'success_div');
            } else {
                $member = array('cmember_id' => $invite->data->invitation_receiver_id,
                    'cmember_community_id' => $invite->data->invitation_entity_id,
                    'cmember_type' => 'U',
                    'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                    //	'cmember_created_by'    => $invite->data->invitation_sender_id,
                    'cmember_status' => 'A'
                );
                $result->status = "SUCCESS";
                $result->message = COMMUNITY_SUCCESS1;
//     			Messages::setPageMessage(COMMUNITY_SUCCESS1,'success_div');
                //Messages::setPageMessage(COMMUNITY_SUCCESS1.$community->data->community_name,'success_div');
            }
            $memberVo = Utils::arrayToObject($member);
            //$memberRes = Connections::acceptCommunityRequest($id,$memberVo);
            $memberRes = Communities::addMembertoCommunity($memberVo);
            Communities::updateCommunityCounts($invite->data->invitation_receiver_id);
            //User::updateUserCount('user_community_count',  PageContext::$response->sess_user_id);
            //echopre($memberRes);
            Communities::updateCommunityCounts();
        }
        echo json_encode($result);
        exit;
    }

    public function view_introduction_invitation($id) {
      
        PageContext::registerPostAction("header", "header_inner", "index", "default");
        PageContext::registerPostAction("leftcontent", "accept_invitation", "index", "default");
        PageContext::addScript('index.js');
        PageContext::addScript('validations_form.js');
        $msg = '';
        $register_flag = 0;
        PageContext::$body_class = 'home';
        PageContext::$response->activeSubMenu = '';
        PageContext::$response->type = $type;
        $invite = Connections::getIntroductionDetails($id);
        //echopre(PageContext::$response->sess_user_id);
        if ($invite->data->introduction_to_user_id != PageContext::$response->sess_user_id) {
            if (PageContext::$response->sess_user_id > 0) { //Logout if already logged in and redirect to accpet again
                //if ($flag == 1) {
                session_destroy();
                session_unset($_SESSION['user']);
                $this->redirect('view-invitation/' . $id);
                //}
            }
        }
        //echopre1($invite);
        if ($invite->status == 'SUCCESS') {
            if ($invite->data->introduction_status != 'S' && $invite->data->introduction_status != '') { //Already responded
                Messages::setPageMessage(INVITATION_ACCEPTED, 'error_div');
                $this->redirect('#jmessage');
            } else {//display login or registration form
                PageContext::$response->id = $id;
                //echopre($_POST);
                if (PageContext::$response->sess_user_id <= 0) {


                    //===========================Login Form================================

                    if (PageContext::$request['btnSubmit'] == 'Sign in') { //=======Post action==============

                        $objUserVo = Utils::arrayToObject($_POST);
                        // echopre1($objUserVo);
                        $objUserRes = User::loginUser($objUserVo);
                        //echopre1($objUserRes);
                        if ($objUserRes->status == 'SUCCESS') {
                            //=============Set Session =============
                            Utils::setSessions($objUserRes->data);
                        } else {
                            Messages::setPageMessage($objUserRes->message, 'error_div');
                        }
//                        }
                        PageContext::$response->message = Messages::getPageMessage();
                    }

//                    PageContext::$response->objForm         = $objFormManager->renderForm();
                    //================ Registration Form =======================
                    $title = "I agree to the <a href='" . BASE_URL . "terms' target='_blank'>Terms of Service</a> and <a href='" . BASE_URL . "privacy-policy' target='_blank'>Privacy Policy</a>.";

                    if (PageContext::$request['btnSubmit'] == 'Sign Up') { //=========Post action========
                        //  echo "here";exit;
                        $msg = '';

                        $unsetArray = array('btnSubmit', 'user_confirm_password', 'terms_conditions');
                        $additionalParameters = array(
                            'user_password' => md5(PageContext::$request['user_password']),
                            'user_created_on' => date('Y-m-d')
                        );
                        $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
                        if (ADMIN_APPROVE_USER_AUTO == 1) {
                            $objUserVo->user_status = 'A';
                            //$msg = REGISTER_SUCCESS;
                        } else {
                            $objUserVo->user_status = 'I';
                            //$msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                        }
                        $objUserRes = User::createUser($objUserVo);
                        if ($objUserRes->status == SUCCESS) {//==========User Registration mail==========
                            $register_flag = 1;
                            $mailIds = array();
                            $replaceparams = array();
                            $mailIds[PageContext::$request['user_email']] = '';
                            $replaceparams['FIRST_NAME'] = $objUserRes->data->user_firstname;
                            $replaceparams['LAST_NAME'] = '';
                            $replaceparams['LOGIN_NAME'] = PageContext::$request['user_email'];
                            $replaceparams['PASSWORD'] = PageContext::$request['user_password'];
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);
                            //Mail to admin
                            $adminemail = Utils::getAdminMail();
                            $mailIds1[$adminemail] = '';
                            $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                            $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                            $replaceparams['USER_EMAIL'] = PageContext::$request['user_email'];
                            $replaceparams['SITE_NAME'] = 'BizBFriend';
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
                            Messages::setPageMessage($msg, 'success_div');
                            //================== set session===================
                            Utils::setSessions($objUserRes->data);
                        } else { //========== User insertion failed ==============
                            Messages::setPageMessage($objUserRes->message, 'error_div');
                        }
//                        }
                        PageContext::$response->regestrationMessage = Messages::getPageMessage();
                    }
//                    PageContext::$response->objRegistrationForm                 = $objFormManager->renderForm();
                }

                $alias = Utils::getAuth('user_id');
                PageContext::$response->sess_user_id = $alias;
                PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
                PageContext::$response->sess_user_email = Utils::getAuth('user_email');
                $userstatus = Utils::getAuth('user_status');
                if ($alias > 0) {
                    $msg = '';
                    $path = 'profile/';
                    if (ADMIN_APPROVE_USER_AUTO == 1) {
                        $msg = REGISTER_SUCCESS;
                        $path = 'view-my-invitation/' . $id;
                    } else {
                        $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                        $path = 'inactiveuser';
                    }
                    if ($userstatus == 'A') {
                        $path = 'view-my-invitation/' . $id;
                    } else if ($userstatus == 'I') {
                        $path = 'inactiveuser';
                    }


                    if ($invite->data->introduction_to_user_email == PageContext::$response->sess_user_email) { //Check if logged in user is same as introduction recipient
                        //if ($type == 'join-community') {
                        $inviteDetails = array(
                            'introduction_to_user_id' => PageContext::$response->sess_user_id,
                            'introduction_to_user_email' => PageContext::$response->sess_user_email
                        );
                        $inviteVo = Utils::arrayToObject($inviteDetails);
                        $inviteRes = Connections::changeIntroductionStatus($id, $inviteVo);
                        $invite = Connections::getIntroductionDetails($id);
                    } else {//Invalid user
                        Messages::setPageMessage('You are not authorised to perform this action', 'error_div');
                        $this->redirect('profile/' . PageContext::$response->sess_user_alias);
                    }

                    // echopre1($path);
                    $this->redirect($path);
                }
            }
        } else {
            Messages::setPageMessage($invite->message, 'error_div');
            $this->redirect('');
        }
    }

    public function accept_pif_invitation($id, $type, $flag = 1, $redirect = '') {

        //PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");
        PageContext::registerPostAction("leftcontent", "accept_pif_invitation", "index", "default");
        PageContext::addScript('index.js');
        PageContext::addScript('validations_form.js');
        $msg = '';
        $register_flag = 0;
        PageContext::$body_class = 'home';
        PageContext::$response->activeSubMenu = '';
        PageContext::$response->type = $type;
        $invite = Connections::getPifDetails($id);
        PageContext::$response->id = $id;
        PageContext::$response->flag = $flag;

        if (PageContext::$response->sess_user_id > 0) { //Logout if already logged in and redirect to accpet again
            if ($flag == 1) {
                if ($redirect == '') {
                    session_destroy();
                    session_unset($_SESSION['user']);
                    $this->redirect('accept-pif-invitation/' . $id . '/' . $type . '/' . $flag);
                }
            }
        }
        //echopre1($invite);
        if ($invite->status == 'SUCCESS') {
            if ($invite->data->pif_status != 'S') { //Already accepted
                Messages::setPageMessage(INVITATION_ACCEPTED, 'error_div');
                $this->redirect('#jmessage');
            } else {

                if (PageContext::$response->sess_user_id <= 0) {
                    //===========================Login Form================================
//                    $arrFormParams                  = array('name' => 'frmLogin', 'id' => 'frmLogin', 'method' => 'post', 'action' => BASE_URL . 'accept-pif-invitation/' . $id . '/' . $type . '/' . $flag, 'class' => '');
//                    $objFormManager                 = new Formmanager($arrFormParams);
                    $mail = (Utils::getCookies('user_email') != '') ? Utils::getCookies('user_email') : PageContext::$request['user_email'];
                    $password = (Utils::getCookies('user_password') != '') ? Utils::getCookies('user_password') : '';
                    $rememberCheck = (Utils::getCookies('user_email') != '') ? 'checked' : '';


                    if (PageContext::$request['btnSubmit'] == 'Sign in') { //=======Post action==============
                        
                        $objUserVo = Utils::arrayToObject($_POST);
                        $objUserRes = User::loginUser($objUserVo);
                        if ($objUserRes->status == 'SUCCESS') {
                            //=============Set Session =============
                            Utils::setSessions($objUserRes->data);
                        } else {
                            Messages::setPageMessage($objUserRes->message, 'error_div');
                        }
//                        }
                        PageContext::$response->message = Messages::getPageMessage();
                    }

                    //PageContext::$response->objForm     = $objFormManager->renderForm();
                    //================ Registration Form =======================
//                    $title                              = "I agree to the <a href='" . BASE_URL . "terms' target='_blank'>Terms of Service</a> and <a href='" . BASE_URL . "privacy-policy' target='_blank'>Privacy Policy</a>.";
//                    $arrFormParams                      = array('name' => 'frmUserRegister', 'id' => 'frmUserRegister', 'method' => 'post', 'action' => BASE_URL . 'accept-pif-invitation/' . $id . '/' . $type . '/' . $flag, 'class' => '');
//                    $objFormManager                     = new Formmanager($arrFormParams);
//                    $arrFormElements                    = array(
//                                                        'user_email' => array('type' => 'text', 'name' => 'user_email', 'value' => PageContext::$request['user_email'], 'size' => 10, 'class' => '', 'placeholder' => 'Your Email',
//                                                            'label' => array('message' => '', 'class' => ''),
//                                                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter email'), 'email' => array('true', 'Please enter a valid email')))),
//                                                        'user_password' => array('type' => 'password', 'name' => 'user_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Password',
//                                                            'label' => array('message' => '', 'class' => ''),
//                                                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please enter password')))),
//                                                        'user_confirm_password' => array('type' => 'password', 'name' => 'user_confirm_password', 'value' => '', 'size' => 10, 'class' => '', 'placeholder' => 'Re-enter Password',
//                                                            'label' => array('message' => '', 'class' => ''),
//                                                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please re-enter password'), 'confirm' => array('true', 'user_password', 'Password mismatch!')))),
//                                                        'terms_conditions' => array('type' => 'checkbox', 'name' => 'terms_conditions', 'value' => '1', 'size' => 10, 'class' => '', 'placeholder' => '', 'title' => $title,
//                                                            'label' => array('message' => '', 'class' => 'checkbox'),
//                                                            'validations' => array('class' => 'clserror', 'options' => array('required' => array('true', 'Please accept the terms and conditions.')))),
//                                                        'btnSubmit' => array('type' => 'submit', 'name' => 'btnSubmit', 'class' => 'yellow_btn', 'value' => 'Sign Up For BizB Friend'),
//                                                    );
//
//                    $objFormManager->addFields($arrFormElements);

                    if (PageContext::$request['btnSubmit'] == 'Sign Up') { //=========Post action========
                        $msg = '';
//                        $objValidator               = new formValidator();
//                        $validation                 = $objValidator->validate($arrFormElements);
//                        if ($validation['error'] == 1) {
//                            $objFormManager->addValidationMessages($validation);
//                        } else {
                        $unsetArray = array('btnSubmit', 'user_confirm_password', 'terms_conditions');
                        $additionalParameters = array(
                            'user_password' => md5(PageContext::$request['user_password']),
                            'user_created_on' => date('Y-m-d')
                        );
                        $objUserVo = Utils::arrayToObject($_POST, $additionalParameters, $unsetArray);
                        if (ADMIN_APPROVE_USER_AUTO == 1) {
                            $objUserVo->user_status = 'A';
                            $msg = REGISTER_SUCCESS;
                        } else {
                            $objUserVo->user_status = 'I';
                            $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                        }
                        $objUserRes = User::createUser($objUserVo);
                        if ($objUserRes->status == SUCCESS) {//==========User Registration mail==========
                            $register_flag = 1;
                            $mailIds = array();
                            $replaceparams = array();
                            $mailIds[PageContext::$request['user_email']] = '';
                            $replaceparams['FIRST_NAME'] = $objUserRes->data->user_firstname;
                            $replaceparams['LAST_NAME'] = '';
                            $replaceparams['LOGIN_NAME'] = PageContext::$request['user_email'];
                            $replaceparams['PASSWORD'] = PageContext::$request['user_password'];
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'user_registration', $replaceparams);
                            //Mail to admin
                            $adminemail = Utils::getAdminMail();
                            $mailIds1[$adminemail] = '';
                            $replaceparams['FIRST_NAME'] = PageContext::$request['user_firstname'];
                            $replaceparams['LAST_NAME'] = PageContext::$request['user_lastname'];
                            $replaceparams['USER_EMAIL'] = PageContext::$request['user_email'];
                            $replaceparams['SITE_NAME'] = 'BizBFriend';
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds1, 'registration_info_admin ', $replaceparams);
                            Messages::setPageMessage($msg, 'success_div');
                            //================== set session===================
                            Utils::setSessions($objUserRes->data);
                        } else { //========== User insertion failed ==============
                            Messages::setPageMessage($objUserRes->message, 'error_div');
                        }
//                        }
                        //PageContext::$response->objRegistrationForm = $objFormManager->renderForm();
                        PageContext::$response->regestrationMessage = Messages::getPageMessage();
                    }
                }

                $alias = Utils::getAuth('user_id');
                PageContext::$response->sess_user_id = $alias;
                PageContext::$response->sess_user_alias = Utils::getAuth('user_alias');
                PageContext::$response->sess_user_email = Utils::getAuth('user_email');
                $userstatus = Utils::getAuth('user_status');
                if ($alias > 0) {
                    $msg = '';
                    //$path = 'profile/';
                    // if (ADMIN_APPROVE_USER_AUTO == 1) {
                    // $msg = REGISTER_SUCCESS;
                    // $path = 'profile/';
                    // } else {
                    // $msg = REGISTER_SUCCESS . ' ' . USER_NOT_ACTIVATED;
                    // $path = 'inactiveuser';
                    // }
                    // if ($userstatus == 'A') {
                    // $path = 'profile/';
                    // } else if ($userstatus == 'I') {
                    // $path = 'inactiveuser';
                    // }
                    if ($invite->data->pif_to_user_email == PageContext::$response->sess_user_email) { //Check if logged in user is same as introduction recipient
                        if ($type == 'join-community') {
                            $inviteDetails = array(
                                'pif_to_user_id' => PageContext::$response->sess_user_id,
                                'pif_to_user_email' => PageContext::$response->sess_user_email,
                                'pif_status' => 'A'
                            );
                            $inviteVo = Utils::arrayToObject($inviteDetails);
                            $inviteRes = Connections::changePifStatus($id, $inviteVo);
                            $invite = Connections::getPifDetails($id);
                            $check = Communities::chekMemeber($invite->data->pif_to_user_id, $invite->data->pif_community_id);
                            if ($check->status == "SUCCESS") {
                                Messages::setPageMessage("You are either a member or sent request to this Bizcom", 'success_div');
                                $path = 'community/' . $invite->data->pif_community_alias;
                                $this->redirect($path);
                            } else {
                                $sender = User::getUserDetail($invite->data->pif_from_user_id);
                                //echopre($invite);
                                $community = Communities::getCommunity($invite->data->pif_community_id);
                                if ($community->data->community_type == 'PRIVATE') {
                                    $member = array('cmember_id' => $invite->data->pif_to_user_id,
                                        'cmember_community_id' => $invite->data->pif_community_id,
                                        'cmember_type' => 'U',
                                        'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                        //  'cmember_created_by'    => $invite->data->invitation_sender_id,
                                        'cmember_status' => 'I',
                                        'cmember_pif_id' => $id,
                                        'cmember_campaign_id' => $invite->data->campaign_id
                                    );
                                    //Messages::setPageMessage('Your membership to Bizcom will be activated by the owner of the community');
                                } else {
                                    //echo $PageContext::$response->sess_user_id;
                                    $member = array('cmember_id' => $invite->data->pif_to_user_id,
                                        'cmember_community_id' => $invite->data->pif_community_id,
                                        'cmember_type' => 'U',
                                        'cmember_joined_on' => date('Y-m-d H:i:s', strtotime('now')),
                                        //	'cmember_created_by'    => $invite->data->invitation_sender_id,
                                        'cmember_status' => 'I',
                                        'cmember_pif_id' => $id,
                                        'cmember_campaign_id' => $invite->data->campaign_id
                                    );
                                    //Messages::setPageMessage('Your membership to Bizcom will be activated by the owner of the community', 'success_div');
                                    //Messages::setPageMessage(REGISTER_SUCCESS . ' ' . COMMUNITY_SUCCESS1, 'success_div');
//     				Messages::setPageMessage(REGISTER_SUCCESS.COMMUNITY_SUCCESS1.$community->data->community_name,'success_div');
                                }
                                //  echopre1($member);
                                //Send Accept Mail to PIF
                                $communityDetails = Communities::getCommunityName($invite->data->pif_community_id);
                                $joineeName = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
                                $joineeEmail = Utils::getAuth('user_email');
                                $mailIds[$invite->data->pif_from_user_email] = '';
                                $replaceparams['NAME'] = $sender->data->Name;
                                $replaceparams['MEMBER_NAME'] = $joineeName;
                                $replaceparams['BIZCOM'] = $communityDetails->data->community_name;
                                $replaceparams['EMAIL'] = $joineeEmail;
                                $replaceparams['SITE_NAME'] = 'BizBFriend';
                                $objMailer = new Mailer();
                                $objMailer->sendMail($mailIds, 'pif_accepted', $replaceparams);
                                //Send Accept Mail to Bizcom Owner
                                $communityOwnerDetails = Communities::getCommunityOwnerDetails($invite->data->pif_community_id);
                                $communityDetails = Communities::getCommunityName($invite->data->pif_community_id);
                                $mailIds1[$communityOwnerDetails->data->user_email] = '';
                                $replaceparams['NAME'] = $userDetails->data->Name;
                                $replaceparams['MEMBER_NAME'] = $joineeName;
                                $replaceparams['PIF_NAME'] = $sender->data->Name;
                                $replaceparams['BIZCOM'] = $communityDetails->data->community_name;
                                $replaceparams['EMAIL'] = $joineeEmail;
                                $replaceparams['SITE_NAME'] = 'BizBFriend';
                                $objMailer = new Mailer();
                                $objMailer->sendMail($mailIds1, 'Pif_accepted_mail_to_owner', $replaceparams);


                                $message_detail = 'You accepted the initiate introduction to join the bizcom  ' . $community->data->community_name;
                                $message_to_id = Utils::getAuth('user_id');
                                $message_from_id = $communityOwnerDetails->data->user_id;
                                $message_date = date('Y-m-d', time());
                                $message_subject = 'PIF Accepted';
                                Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);

                                $message_detail = 'A new member has accepted the initiate introduction to join the bizcom  ' . $community->data->community_name . '  by ' . $joineeName;
                                $message_to_id = $communityOwnerDetails->data->user_id;
                                $message_from_id = Utils::getAuth('user_id');
                                $message_date = date('Y-m-d', time());
                                $message_subject = 'PIF Accepted';
                                Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);


                                $memberVo = Utils::arrayToObject($member);
                                //$memberRes = Connections::acceptCommunityRequest($id,$memberVo);
                                $memberRes = Communities::addMembertoCommunity($memberVo);
                                Communities::updateCommunityCounts(PageContext::$response->sess_user_id);
                                //User::updateUserCount('user_community_count',  PageContext::$response->sess_user_id);
                                //echopre($memberRes);
                            }
                        } elseif ($type == 'reject') {
                            $inviteDetails = array('pif_status' => 'D'
                            );
                            $inviteVo = Utils::arrayToObject($inviteDetails);
                            $inviteRes = Connections::changePifStatus($id, $inviteVo);
                            Messages::setPageMessage('You have rejected the request', 'success_div');

                            //Send Reject Mail
                            $communityDetails = Communities::getCommunityName($invite->data->pif_community_id);
                            $communityOwnerDetails = Communities::getCommunityOwnerDetails($invite->data->pif_community_id);
                            $joineeName = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
                            $joineeEmail = Utils::getAuth('user_email');
                            //$mailIds[$invite->data->introduction_from_user_email] = '
                            $mailIds[$invite->data->pif_from_user_email] = '';
                            $replaceparams['NAME'] = $sender->data->Name;
                            $replaceparams['MEMBER_NAME'] = $joineeName;
                            $replaceparams['BIZCOM'] = $communityDetails->data->community_name;
                            $replaceparams['EMAIL'] = $joineeEmail;
                            $replaceparams['SITE_NAME'] = 'BizBFriend';
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'pif_rejected', $replaceparams);

                            $message_detail = 'You rejected the initiate introduction to join the bizcom  ' . $community->data->community_name;
                            $message_to_id = Utils::getAuth('user_id');
                            $message_from_id = $communityOwnerDetails->data->user_id;
                            $message_date = date('Y-m-d', time());
                            $message_subject = 'PIF Rejected';
                            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);

                            $message_detail = $joineeName . ' has rejected the initiate introduction to join the bizcom  ' . $community->data->community_name;
                            $message_to_id = $communityOwnerDetails->data->user_id;
                            $message_from_id = Utils::getAuth('user_id');
                            $message_date = date('Y-m-d', time());
                            $message_subject = 'PIF Rejected';
                            Connections::sendMessages($message_detail, $message_to_id, $message_from_id, $message_date, $message_subject);
                            //	Messages::setPageMessage(REJECT_SUCCESS.$sender->data->Name,'success_div');
                        }
                    }
                    //Redirection
                    if ($type == 'reject') {
                        if ($register_flag == 1) {
                            Messages::setPageMessage(REGISTER_SUCCESS . ' ' . REJECT_SUCCESS, 'success_div');
                        } else {
                            Messages::setPageMessage(REJECT_SUCCESS, 'success_div');
                        }
                        $path = 'profile/' . PageContext::$response->sess_user_alias;
                    } else {
                        if ($register_flag == 1) {
                            Messages::setPageMessage(REGISTER_SUCCESS . ' ' . COMMUNITY_SUCCESS1 . ' ' . COMMUNITY_SUCCESS_APPROVAL, 'success_div');
                        } else {
                            Messages::setPageMessage(COMMUNITY_SUCCESS1 . ' ' . COMMUNITY_SUCCESS_APPROVAL, 'success_div');
                        }
                        //$path = 'inactiveuser';
                        $path = 'profile/' . PageContext::$response->sess_user_alias;
                    }

                    $this->redirect($path);
                }
            }
        } else {
            Messages::setPageMessage($invite->message, 'error_div');
            $this->redirect('profile/' . PageContext::$response->sess_user_alias);
        }
    }

    //Invite Friend throgh invite option and send mail to accept
    public function inviteFriendsthroughMail($type, $id) {
        $result = new stdClass();
        $list1 = explode(',', $_REQUEST["contacts_check"]);
        $length1 = sizeof($list1);
        if ($length1 > 1) { //==========Post action==========    			    			 
            $contactList = $_REQUEST["contact_list"];
            Logger::info($_REQUEST);
            $list = explode(',', $_REQUEST["contacts_check"]);
            Logger::info($list);
            $flag = 0;
            $message = '';
            $replaceparams = array();
            $length = sizeof($list);
            $count = 0;
            $notSendList = '';
            $notSendCount = 0;
            if ($type == 'user') { //Friend invitation
                for ($i = 0; $i < $length; $i++) {
                    if ($list[$i] != '') {
                        $mailIds = array();
                        $invitations = array('invitation_type' => 'E', //E->Email U ->User
                            'invitation_entity' => 'U', //U->user C->Community
                            'invitation_entity_id' => $id,
                            'invitation_sender_email' => PageContext::$response->sess_user_email,
                            'invitation_sender_id' => PageContext::$response->sess_user_id,
                            'invitation_receiver_email' => $list[$i],
                            'invitation_receiver_id' => 0,
                            'invitation_status' => 'P', //Pending
                            'mail_template' => 'invite'
                        );
                        //check if invitation already sent
                        $invitationSentCount = Connections::checkInvitationSentEmail(PageContext::$response->sess_user_id, $list[$i], 'U', $id);
                        if ($invitationSentCount == 0) {
                            $objInvitationsVo = Utils::arrayToObject($invitations);
                            $objInvitationRes = Connections::addInvitation($objInvitationsVo);
                            Logger::info($objInvitationRes);
                            if ($objInvitationRes->status != SUCCESS) {
                                $flag = 1;
                                $message = $objInvitationRes->message;
                            }
                            $replaceparams['EMAIL'] = $list[$i];
                            $replaceparams['INVITE_ID'] = $objInvitationRes->invitation_id;
                            $replaceparams['NAME'] = PageContext::$response->sess_user_name;
                            $replaceparams['IMG_URL'] = USER_IMAGE_URL_DEFAULT;
                            $replaceparams['INVITE_TYPE'] = 'join';
                            $mailIds[$list[$i]] = '';
                            $objMailer = new Mailer();
                            $objMailer->sendMail($mailIds, 'invite', $replaceparams); //send invitation mail
                            $count++;
                        } else {//Get the not sent list  and count
                            if ($notSendCount != 0) {
                                $notSendList = $notSendList . ", ";
                            }
                            $notSendList = $notSendList . $list[$i];
                            $notSendCount++;
                        }
                    }
                }
            }
            Logger::info($mailIds);
            if ($flag == 0) {
                if ($notSendCount > 0) {
                    $msg = "Mail already sent to " . $notSendList;
                } else {
                    $msg = '';
                }
                $result = Messages::getPageMessage();
                if ($count > 0) { //If invitation sent count is greater than 0
                    $class = 'success_div';
                } else {
                    $class = 'error_div';
                }
                $result = INVITATION_SEND_SUCCESS . " to $count person(s). $msg";
            } else { //========User invitation failed =======
                Messages::setPageMessage(INVITATION_SEND_FALIURE, 'error_div');
                $result = Messages::getPageMessage();
                $result = INVITATION_SEND_FALIURE;
                $class = 'error_div';
            }
        } else {
            $result = CONTACTS_NOT_SELECTED;
            $class = 'error_div';
        }
        $data = array("msg" => $result, "cls" => $class);
        echo json_encode($data);
        exit;
    }

    /*
     * Contact Us 
     */

    public function contact() {
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "contact", "index", "default");
        if (PageContext::$request['btnSubmit']) { //=======Post action=========
            //Mail to admin
            $adminemail = Utils::getAdminMail();
            $mailIds1[$adminemail] = '';
            $replaceparams['SENDER_EMAIL'] = $_POST['sender_email'];
            $replaceparams['SUBJECT'] = stripslashes($_POST['email_subject']);
            $replaceparams['BODY'] = stripslashes($_POST['email_description']);
//            echopre($replaceparams);exit;
            $objMailer = new Mailer();
            $flag = $objMailer->sendMail($mailIds1, 'contactus_mail ', $replaceparams);
            if ($flag == '0') {
                Messages::setPageMessage('Mail Could not be sent', 'error_div');
            } else {
                Messages::setPageMessage('Thanks! We appreciate that you’ve taken the time to write us. We’ll get back to you very soon.', 'success_div');
            }
            PageContext::$response->message = Messages::getPageMessage();
        }
    }

    public function refer_friend() {
        PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");
        PageContext::registerPostAction("leftcontent", "refer_friend", "index", "default");

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        if (PageContext::$request['btnSubmit']) {
            $mailIds = array();
            $friend_mail = $_POST['friend_email'];
            $mailIds[$friend_mail] = '';
            $replaceparams['SENDER_NAME'] = PageContext::$response->sess_user_name;
            $replaceparams['SITE_NAME'] = 'BizBFriend';
            $replaceparams['IMG_URL'] = SITE_LOGO;
            $objMailer = new Mailer();
            $flag = $objMailer->sendMail($mailIds, 'referafriend_mail', $replaceparams);
            if ($flag == '0') {
                Messages::setPageMessage('Mail Could not be sent', 'error_div');
            } else {
                Messages::setPageMessage('Your Invitation Sent Successfully', 'success_div');
            }
            PageContext::$response->message = Messages::getPageMessage();
        }
    }

    public function refer_friend_community() {
        PageContext::registerPostAction("rightcontent", "rightcontent", "index", "default");
        PageContext::registerPostAction("leftcontent", "refer_friend_community", "index", "default");

        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();
        if (PageContext::$request['btnSubmit']) {
            $url = $_GET['url'];
            $community_url = explode("community/", $url);
            $community_name = Communities::getCommunityNameByAlias($community_url[1]);

            $mailIds = array();
            $friend_mail = $_POST['friend_email'];
            $mailIds[$friend_mail] = '';
            $replaceparams['COMMUNITY_NAME'] = $community_name->community_name;
            $replaceparams['SITE_NAME'] = 'BizBFriend';
            $replaceparams['PAGE_URL'] = $url;
            //  $replaceparams['IMG_URL']                         = SITE_LOGO;
            $objMailer = new Mailer();
            $flag = $objMailer->sendMail($mailIds, 'refer_friend_community', $replaceparams);
            if ($flag == '0') {
                Messages::setPageMessage('Mail Could not be sent', 'error_div');
            } else {
                Messages::setPageMessage('Your Invitation Sent Successfully', 'success_div');
            }
            PageContext::$response->message = Messages::getPageMessage();
        }
    }

    /*
     * Feedback 
     */

    public function feedback() {
        if (PageContext::$response->sess_user_id > 0) {
            PageContext::registerPostAction("header", "header_inner", "user", "default");
        } else {
            PageContext::registerPostAction("header", "header_login", "index", "default");
        }
        PageContext::registerPostAction("rightcontent", "rightmenu", "user", "default");
        PageContext::registerPostAction("leftcontent", "feedback", "index", "default");
        if (PageContext::$request['btnSubmit']) { //=======Post action=========
            //Mail to admin
            $adminemail = Utils::getAdminMail();
            $mailIds1[$adminemail] = '';
            $replaceparams['SENDER_NAME'] = $_POST['sender_name'];
            $replaceparams['SENDER_EMAIL'] = $_POST['sender_email'];
            $replaceparams['SUBJECT'] = stripcslashes($_POST['email_subject']);
            $replaceparams['BODY'] = stripcslashes($_POST['email_description']);
//            echopre($replaceparams);exit;
            $objMailer = new Mailer();
            $flag = $objMailer->sendMail($mailIds1, 'feedback_mail ', $replaceparams);
            if ($flag == '0') {
                Messages::setPageMessage('Mail Could not be sent', 'error_div');
            } else {
                Messages::setPageMessage('Thanks! We appreciate that you’ve taken the time to write us. We’ll get back to you very soon.', 'success_div');
            }
            PageContext::$response->message = Messages::getPageMessage();
        }
    }

    public function friendautocomplete() {
        // echo $_REQUEST['term'];exit;
        $result = User::getFriendName($_REQUEST['term']);
        $data = array();
        foreach ($result as $k => $v) {
            $data[] = Utils::objectToArray($v);
        }
        echo json_encode($data);
        exit;
    }

}

?>
