<?php

/*
 * All Community Entity Logics should come here.
 */

class Communities {
    /*
      Function to Register a  new Community
     */

    public static function createCommunity($objCommunityVo) {
        //echopre($objCommunityVo);exit;
        $objResult                      = new Messages();
        $objMember                      = new stdClass();
        $objResult->status              = SUCCESS;
        $data                           = array();
        if ($objResult->status == SUCCESS) {
            $db                         = new Db();
            $tableName                  = Utils::setTablePrefix('communities');
            $excludeId                  = '';
            $CommunityAliasName         = Utils::generateAlias($tableName, $objCommunityVo->community_name, $idColumn = "community_id", $id = $excludeId, $aliasColumn = "community_alias");
            $data                       = Utils::objectToArray($objCommunityVo);
            $data['community_alias']    = $CommunityAliasName;
            //echopre1($data);
            $communityId                = $db->insert($tableName, $data);
            $objResult->community_id    = $communityId;
            $objResult->data            = $objCommunityVo;
            $objMember->cmember_community_id = $communityId;
            $objMember->cmember_id      = $data['community_created_by'];
            $objMember->cmember_type    = 'A';
            $objMember->cmember_joined_on = date('Y-m-d H:i:s');
            $objMember->cmember_status  = 'A';
            self::addMembertoCommunity($objMember);
        }
        Logger::info($objResult);
        return $objResult;
    }
    /*
      Function to edit Community information
     * Parameter -  Community Data
     */

    public function editCommunity($communityId = '', $objCommunityVo) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $data = array();
        //Check Entered User Email Exists OR NOT then stop user sign up if email exists
        if ($communityId == '') {
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Email Alreday Exists
        }

        // Update Community data to  Community table 
        if ($objResult->status == SUCCESS) {
            $db = new Db();
            $tableName = Utils::setTablePrefix('communities');
            $where = "community_id = " . $db->escapeString($communityId) . " ";
            $data = Utils::objectToArray($objCommunityVo);
            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
            $objUserVo->community_id = $communityId;
            $objResult->data = $objCommunityVo;
        }
        Logger::info($objResult);
        return $objResult;
    }

    /*
      Function to Change Community Status
     * Parameters  : Community Id 
     */

    public static function changeCommunityStatus($communityId, $objCommunityVo = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //  Check Entered Community Id   exists in the system
        if ($communityId != '') {

            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Community Id  not  Exists
        }
        // Update User status to deleted  if community  already exists
        if ($objResult->status == SUCCESS) {

            $db = new Db();
            $tableName = Utils::setTablePrefix('communities');
            $selectCase = '';

            $where = "community_id='" . $db->escapeString($communityId) . "' ";
            $resultRows = $db->update($tableName, array('community_status' => $db->escapeString($objCommunityVo->community_status),
                    ), $where, $doAudit = false);
            // Update  User Account with deleted status  and Set Corresponding Message
            if ($resultRows > 0) {
                $objResult->message = COMMUNITY_DELETED_SUCCESS; // User Deleted Successfully
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    public function listCommunities($objTableVo) {
        if ($objTableVo->coulmns == '') {
            $objTableVo->coulmns = '*';
        }

        $objTableVo->tablename = 'communities';
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $db = new Db();
        $objResultRows = $db->getPagingData($objTableVo->coulmns, $objTableVo->tablename, $objTableVo->join, $objTableVo->criteria, $objTableVo->community_by, $objTableVo->sort_order, $objTableVo->sort_field, $objTableVo->limit);
        //Check User Details exist 
        if ($objResultRows)
        // Assign User details to object
            $objResult->data = $objResultRows;
        else {
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_NOT_EXIST; // Store details not exists 
        }

        Logger::info($objResult);

        return $objResult;
    }

    /*
      Function to get Community details
     * Parameters  : Community id
     */

    public static function getCommunity($communityId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($communityId != '') {
            $db = new Db();
            $tableName = 'communities';
            $selectCase = '  community_id =' . $db->escapeString($communityId) . ' ';
            Logger::info($selectCase);

            $objResultRow = $db->selectRecord($tableName, '*', $selectCase);
            // If community exists then assign community data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    public static function getCommunityId($alias = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($alias != '') {
            $db = new Db();
            $business = Utils::setTablePrefix('communities');


            $query = "SELECT community_id from $business WHERE community_alias ='" .$db->escapeString($db->escapeString($alias)) . "' ";


            Logger::info($query);

            $objResultRow = $db->fetchSingleRow($query);

            // If buisiness exists then assign buisiness data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign buisiness record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST; // Buisiness not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }
    
     public static function getCommunityAliasFromId($id = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($id != '') {
            $db = new Db();
            $business = Utils::setTablePrefix('communities');


            $query = "SELECT community_alias from $business WHERE community_id ='" . $db->escapeString($id) . "' ";


            Logger::info($query);

            $objResultRow = $db->fetchSingleRow($query);

            // If buisiness exists then assign buisiness data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign buisiness record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST; // Buisiness not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    /*
      Function to get Community details
     * Parameters  : Community alias
     */

    public static function getCommunityAlias($communityId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($communityId != '') {
            $db = new Db();
            $tableName = 'communities';
            $selectCase = '  community_id =' . $db->escapeString($communityId) . ' ';

            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');
            $category = Utils::setTablePrefix('categories');
            
            $community_member = Utils::setTablePrefix('community_member');
            $business = Utils::setTablePrefix('businesses');
           $query = "SELECT community_business_id from $community WHERE community_id ='" . $db->escapeString($communityId) . "' ";


            //Logger::info($query);

            $objResultRow1 = $db->fetchSingleRow($query);
            if($objResultRow1->community_business_id == 0)
            {
            //echopre1($objResultRow);
             $query = "SELECT  c.*, u.*, f.*,ifnull(b.business_name,'Personal')AS business_name,b.business_alias, m.cmember_id,m.cmember_active_status,ct.category_name FROM $community c "
                     . "LEFT JOIN $files f ON c.community_image_id = f.file_id "
                     . "LEFT JOIN $users u ON c.community_created_by = u.user_id "
                     . "LEFT JOIN $business b ON b.business_id=c.community_business_id "
                     . "LEFT JOIN $community_member m ON m.cmember_community_id = c.community_id LEFT JOIN $category AS ct ON "
                     . "c.community_category_id = ct.category_id"
                     . " WHERE c.community_id = '" . $db->escapeString($communityId) . "' ";
            }
            else{
                $query = "SELECT  c.*, u.*, f.*,ifnull(b.business_name,'Personal')AS business_name,b.business_alias, m.cmember_id,m.cmember_active_status,ct.category_name FROM $community c "
                     . "LEFT JOIN $files f ON c.community_image_id = f.file_id "
                     . "LEFT JOIN $users u ON c.community_created_by = u.user_id "
                     . "LEFT JOIN $business b ON b.business_id=c.community_business_id "
                     . "LEFT JOIN $community_member m ON m.cmember_community_id = c.community_id LEFT JOIN $category AS ct ON "
                     . "b.business_category_id = ct.category_id"
                     . " WHERE c.community_id = '" . $db->escapeString($communityId) . "' ";

            }
//echo $query;
            Logger::info($query);

            $objResultRow = $db->fetchSingleRow($query);
            // If community exists then assign community data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = COMMUNITY_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    public static function getCommunityAliasname($communityId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($communityId != '') {
            $db = new Db();
            $tableName = 'communities';
            $selectCase = '  community_id =' . $db->escapeString($communityId) . ' ';

            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');
            
            $community_member = Utils::setTablePrefix('community_member');
            $business = Utils::setTablePrefix('businesses');

             $query = "SELECT  c.*, u.*, f.*,ifnull(b.business_name,'Personal')AS business_name, m.cmember_id FROM $community c "
                     . "LEFT JOIN $files f ON c.community_image_id = f.file_id "
                     . "LEFT JOIN $users u ON c.community_created_by = u.user_id "
                     . "LEFT JOIN $business b ON b.business_id=c.community_business_id "
                     . "LEFT JOIN $community_member m ON m.cmember_community_id = c.community_id"
                     . " WHERE c.community_alias = '" . $db->escapeString($communityId) . "' ";

//echo $query
            Logger::info($query);

            $objResultRow = $db->fetchSingleRow($query);
            // If community exists then assign community data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = COMMUNITY_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }
    public static function getCommunitySearch($searchString) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($searchString != '') {
            $db = new Db();

            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');

            $query = "SELECT  c.community_name as label, c.community_alias as value, f.file_path as image,'community' AS type 
                     FROM $community c LEFT JOIN $files f ON c.community_image_id = f.file_id 
                     LEFT JOIN $users u ON c.community_created_by = u.user_id 
                     WHERE c.community_name like '%" . $searchString . "%'  AND c.community_status = 'A' limit 3";

            //  echo $query;
            Logger::info($query);

            $objResultRow = $db->fetchAll($db->execute($query));
            // If community exists then assign community data to result object
        }

        Logger::info($objResultRow);
        return $objResultRow;
    }

    // Function to Add community to a Community

    public static function addMembertoCommunity($objMemVo,$community_owner) {

   //   echopre1($objMemVo);
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $data = array();
        //echo $objMemVo['cmember_id']."----".$objMemVo->cmember_community_id;
        if ($objMemVo->cmember_id == '' || $objMemVo->cmember_community_id == '') {

           // echo "here";exit;
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Community Id  not  Exists
        }

        if ($objResult->status == SUCCESS) {
           // echo "jfhjdf";exit;
            $db = new Db();
            $tableName = Utils::setTablePrefix('community_member');
            $tableName1 = Utils::setTablePrefix('users');
            $data = Utils::objectToArray($objMemVo);
           // echopre1($data);
            $query = "SELECT count(*) AS  c from $tableName WHERE cmember_id = '" . $objMemVo->cmember_id . "' AND cmember_community_id = '" . $objMemVo->cmember_community_id . "' AND cmember_status = 'P' AND cmember_active_status = 'P'";
            Logger::info($query);
            $objResultRow = $db->selectQuery($query);
            $count = ($objResultRow[0]->c) ? $objResultRow[0]->c : 0;
            //echo $count;exit;
           // echopre1($data);
            if($count == 0){
            $communityId = $db->insert($tableName, $data);
            if($objMemVo->cmember_type !='A' && $objMemVo->cmember_status =='P'){
            $where                          = '  user_id =' . $db->escapeString($community_owner);
            $user_private_request_count                 = $db->selectRow('users', 'user_private_request_count', $where);
            $user_private_request_count++;
            $db->update($tableName1, array('user_private_request_count' => $user_private_request_count), $where, $doAudit = false);
            }
            }
            $objMemVo->cmember_list_id = $communityId;
            $objResult->data = $objMemVo;
        }

        Logger::info($objResult);
        return $objResult;
    }

    // Function to Edit Member Status

    public function chanegeMemeberCommunityStatus($objMemVo) {


        $objResult = new Messages();
        $objResult->status = SUCCESS;


        if ($objMemVo->cmember_id == '' || $objMemVo->cmember_community_id == '') {
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Email Alreday Exists
        }



        // Update Community data to  Community Member table 

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

            $db = new Db();

            $tableName = Utils::setTablePrefix('community_member');
            $where = "cmember_id = " . $db->escapeString($objMemVo->cmember_id) . " AND cmember_community_id = " . $db->escapeString($objMemVo->cmember_community_id) . " ";
            $customerId = $db->update($tableName, array('cmember_status' => $db->escapeString($objMemVo->cmember_status),
                    ), $where, $doAudit = false);
            $objUserVo->cmember_id = $objMemVo->cmember_id;
            $objResult->data = $objMemVo;
        }

        Logger::info($objResult);

        return $objResult;
    }

    public function deleteMemeberCommunityStatus($objMemVo) {


        $objResult = new Messages();
        $objResult->status = SUCCESS;


        if ($objMemVo->cmember_id == '' || $objMemVo->cmember_community_id == '') {
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Email Alreday Exists
        }



        // Update Community data to  Community Member table 

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

            $db = new Db();

            $tableName = Utils::setTablePrefix('community_member');
            $where = "cmember_id = " . $db->escapeString($objMemVo->cmember_id) . " AND cmember_community_id = " . $db->escapeString($objMemVo->cmember_community_id) . " ";
            $customerId = $db->delete($tableName, $where, $doAudit = false);
            $objUserVo->cmember_id = $objMemVo->cmember_id;
            $objResult->data = $objCommunityVo;
        }

        Logger::info($objResult);

        return $objResult;
    }

    public static function updateCommunityRegisterTime($communityId) {
        $db = new Db();
        $table = 'communities';
        $dataArray = array();

        $data = $db->selectRecord($table, 'community_name,community_image_id', 'community_id = ' . $communityId);
        if ($data->community_image_id > 0) {
            $file = $db->selectRow('files', 'file_path', 'file_id = ' . $data->community_image_id);
            if($width >= 256 || $height >= 242){
                
            Utils::allResize($file, 'medium', 256, 242);
            Utils::allResize($file, 'small', 190, 134);
            Utils::allResize($file, 'thumb', 50, 50);
            }
            else{
            Utils::allResize($image, 'medium', $width, $height);
            //Utils::allResize($image, 'small', $width, $height);
            if($width >= 190 || $height >= 134){
                Utils::allResize($image, 'small', 190, 134);
                
            }
            else{
               Utils::allResize($image, 'small', $width, $height); 
            }
            if($width >= 50 || $height >= 50){
                Utils::allResize($image, 'thumb', 50, 50);
                
            }
            else{
               Utils::allResize($image, 'thumb', $width, $height); 
            }
            }
            
//            Utils::allResize($file, 'medium', 256, 242);
//            Utils::allResize($file, 'small', 190, 134);
//            Utils::allResize($file, 'thumb', 50, 50);
        }
        $communityAliasName = Utils::generateAlias(MYSQL_TABLE_PREFIX . $table, $data->community_name, $idColumn = "community_id", $id = $excludeId, $aliasColumn = "community_alias");
        $dataArray['community_alias'] = $communityAliasName;
        $dataArray['community_status'] = 'A';
        $dataArray['community_created_on'] = date('Y-m-d H:i:s');

        $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'community_id="' . $db->escapeString($communityId) . '"');
    }

//    public static function updateCommunityFile($userId) {
//        $db = new Db();
//        $table = 'communities';
//
//        $data = $db->selectRow($table, 'community_image_id', 'community_id = ' . $userId);
//        //echopre($data);
//        //exit;
//        $file = $db->selectRow('files', 'file_path', 'file_id = ' . $data);
//        if($width >= 256 || $height >= 242){
//                
//            Utils::allResize($file, 'medium', 256, 242);
//            Utils::allResize($file, 'small', 190, 134);
//            Utils::allResize($file, 'thumb', 50, 50);
//            }
//            else{
//            Utils::allResize($image, 'medium', $width, $height);
//            //Utils::allResize($image, 'small', $width, $height);
//            if($width >= 190 || $height >= 134){
//                Utils::allResize($image, 'small', 190, 134);
//                
//            }
//            else{
//               Utils::allResize($image, 'small', $width, $height); 
//            }
//            if($width >= 50 || $height >= 50){
//                Utils::allResize($image, 'thumb', 50, 50);
//                
//            }
//            else{
//               Utils::allResize($image, 'thumb', $width, $height); 
//            }
//            }
//        
////        Utils::allResize($file, 'medium', 256, 242);
////        Utils::allResize($file, 'small', 190, 134);
////        Utils::allResize($file, 'thumb', 50, 50);
//        //	$db->update(MYSQL_TABLE_PREFIX.$table, $dataArray,'community_id="'.mysql_real_escape_string($userId).'"');
//    }

    public static function getAllCommunity($orderfield = 'community_name', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '', $userMode = '',$groupby = '',$groupbystatus='') {
//echo $orderby;exit;
        $db = new Db();

        $files = Utils::setTablePrefix('files');

        $users = Utils::setTablePrefix('users');

        $members = Utils::setTablePrefix('community_member');
        $business = Utils::setTablePrefix('businesses');

        if ($userId > 0) {
            if ($userMode == 'A') {//Admin level check
                $userWhere = "m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' ";
            } 
            //Member level check
            else if ($userMode == 'U') {
                $userWhere = "m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' ";
            }
            else {//Both admin and members
                $userWhere = "m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' ";
            }
        } else {
            $userWhere = "c.community_status != 'D'";
        }
        if($groupby){
           $userWhere .= ' AND c.community_category_id  = '.$groupby;
      }
        if($groupbystatus){
            if($groupbystatus == 'P')
           $userWhere .= " AND m.cmember_active_status  = 'P' ";
            else
                $userWhere .= " AND m.cmember_active_status  = 'A' ";
        }
        $objLeadData = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key = 'c.community_id';
        $objLeadData->fields = "c.*,f.*,u.*,ifnull(b.business_name,'Personal')AS business_name,m.cmember_active_status";
        $objLeadData->join = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                                LEFT JOIN $users as u ON c.community_created_by = u.user_id 
                                LEFT JOIN $members m ON c.community_id = m.cmember_community_id
                                LEFT JOIN $business b ON b.business_id=c.community_business_id";
        $objLeadData->where = "$userWhere ";
        //  echo $objLeadData->where;

        if ($search != '') {
            $objLeadData->where .= " AND (";
            $fieldsize = sizeof($searchFieldArray);
            $i = 1;
            foreach ($searchFieldArray AS $searchField) {
                $objLeadData->where .= " $searchField LIKE '%$search%' ";
                if ($i == $fieldsize) {
                    $objLeadData->where .= " )";
                } else {
                    $objLeadData->where .= " OR";
                }
                $i++;
            }
        }
        $objLeadData->groupbyfield = 'c.community_id';
        $objLeadData->orderby = $orderby;
        $objLeadData->orderfield = $orderfield;
        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
       //  echopre($leads);
        //return $leads->records;
        return $leads;
    }
    
        public static function getCommunities($orderfield = 'community_name', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '', $userMode = '',$groupby) {
//echo $userId;exit;
        $db = new Db();

        $files = Utils::setTablePrefix('files');

        $users = Utils::setTablePrefix('users');

        $members = Utils::setTablePrefix('community_member');
        $business = Utils::setTablePrefix('businesses');

        if ($userId > 0) {
            if ($userMode == 'A') {//Admin level check
                $userWhere = "m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' AND m.cmember_type='A'";
            } 
            //Member level check
            else if ($userMode == 'U') {
                $userWhere = " c.community_status != 'D' AND m.cmember_type='U'";
            }
            else {//Both admin and members
                $userWhere = "c.community_status != 'D' ";
            }
        } else {
            $userWhere = "c.community_status != 'D' AND community_type = 'PUBLIC' ";
        }
      if($groupby){
           $userWhere .= ' AND c.community_category_id  = '.$groupby;
      }
        $objLeadData = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key = 'c.community_id';
        $objLeadData->fields = "c.*,f.*,ifnull(b.business_name,'Personal')AS business_name";
        $objLeadData->join = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                              LEFT JOIN $business b ON b.business_id=c.community_business_id";
        $objLeadData->where = "$userWhere ";
        //  echo $objLeadData->where;

        if ($search != '') {
            $objLeadData->where .= " AND (";
            $fieldsize = sizeof($searchFieldArray);
            $i = 1;
            foreach ($searchFieldArray AS $searchField) {
                $objLeadData->where .= " $searchField LIKE '%$search%' ";
                if ($i == $fieldsize) {
                    $objLeadData->where .= " )";
                } else {
                    $objLeadData->where .= " OR";
                }
                $i++;
            }
        }
        $objLeadData->groupbyfield = 'c.community_id';   
        $objLeadData->orderby = $orderby;
        $objLeadData->orderfield = $orderfield;
        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
      //   echopre($leads);
        //return $leads->records;
        return $leads;
    }
    
    public static function getAllActiveCommunity($orderfield = 'community_name', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '', $userMode = '') {
//echo $userId;exit;
        $db = new Db();

        $files = Utils::setTablePrefix('files');

        $users = Utils::setTablePrefix('users');

        $members = Utils::setTablePrefix('community_member');
        $business = Utils::setTablePrefix('businesses');
        $userWhere .= "c.community_status = 'A'  ";
        if ($userId > 0) {
            if ($userMode == 'A') {//Admin level check
                $userWhere.= " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' AND m.cmember_type='A'";
            } 
            //Member level check
            else if ($userMode == 'U') {
                $userWhere .= " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' AND m.cmember_type='U'";
            }
            else {//Both admin and members
                $userWhere .= " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D' ";
            }
        } 
            
        

        $objLeadData = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key = 'c.community_id';
        $objLeadData->fields = "c.*,f.*,u.*,ifnull(b.business_name,'Personal')AS business_name";
        $objLeadData->join = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                                LEFT JOIN $users as u ON c.community_created_by = u.user_id 
                                LEFT JOIN $members m ON c.community_id = m.cmember_community_id
                                LEFT JOIN $business b ON b.business_id=c.community_business_id";
        $objLeadData->where = "$userWhere ";
        //   echo $objLeadData->where;

        if ($search != '') {
            $objLeadData->where .= " AND (";
            $fieldsize = sizeof($searchFieldArray);
            $i = 1;
            foreach ($searchFieldArray AS $searchField) {
                $objLeadData->where .= " $searchField LIKE '%$search%' ";
                if ($i == $fieldsize) {
                    $objLeadData->where .= " )";
                } else {
                    $objLeadData->where .= " OR";
                }
                $i++;
            }
        }
        $objLeadData->groupbyfield = 'c.community_id';
        $objLeadData->orderby = $orderby;
        $objLeadData->orderfield = $orderfield;
        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
        // echopre($leads);
        //return $leads->records;
        return $leads;
    }

    public static function getCommunityInvitationReport($communityAlias, $pagenum = 1, $itemperpage, $search = '') {

        $db = new Db();

        $community_member = Utils::setTablePrefix('community_member');

        $users = Utils::setTablePrefix('users');

        $invitation = Utils::setTablePrefix('invitation');

        $community = Utils::setTablePrefix('communities');
        $userWhere = "i.invitation_entity = 'C' AND c.community_alias = '" . $db->escapeString($communityAlias) . "'";

        if ($search) {
            $userWhere.="AND (CONCAT(u.user_firstname,u.user_lastname) LIKE  '%$search%' OR u.user_email LIKE '%$search%') ";
        }


        $objLeadData = new stdClass();
        $objLeadData->table = 'invitation AS i';
        $objLeadData->key = 'i.invitation_id';
        $objLeadData->fields = 'i.*,u.*';
        $objLeadData->join = " LEFT JOIN  $community c ON c.community_id = i.invitation_entity_id  LEFT JOIN $users u ON i.invitation_sender_id = u.user_id  ";
        $objLeadData->where = "$userWhere ";
        //   echo $objLeadData->where;
        //$objLeadData->groupbyfield  = 'u.user_id';
        $objLeadData->orderby = '';
        $objLeadData->orderfield = '';

        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
//          echopre($leads);
        //return $leads->records;
        return $leads;
    }

    public static function getCommunityInvitationCount($communityAlias) {

        $db = new Db();

        $community_member = Utils::setTablePrefix('community_member');

        $users = Utils::setTablePrefix('users');

        $invitation = Utils::setTablePrefix('invitation');

        $community = Utils::setTablePrefix('communities');
        $userWhere = "WHERE i.invitation_entity = 'C' AND c.community_alias = '" . $db->escapeString($db->escapeString($communityAlias)) . "'";

        if ($search) {
            $userWhere.="AND (CONCAT(u.user_firstname,u.user_lastname) LIKE  '%$search%' OR u.user_email LIKE '%$search%') ";
        }


        $objLeadData = new stdClass();
        $objLeadData->table = 'invitation AS i';
        $objLeadData->key = 'i.invitation_id';
        $objLeadData->fields = 'i.*,u.*';
        $objLeadData->join = " LEFT JOIN  $community c ON c.community_id = i.invitation_entity_id  LEFT JOIN $users u ON i.invitation_sender_id = u.user_id  ";
        $objLeadData->where = "$userWhere ";
        //   echo $objLeadData->where;
        //$objLeadData->groupbyfield  = 'u.user_id';
        $objLeadData->orderby = '';
        $objLeadData->orderfield = '';

        //$objLeadData->itemperpage   = $itemperpage;
        //$objLeadData->page	    = $pagenum;		// by default its 1
        $objLeadData->debug = true;
        $leads = $db->getAllData('i.*', $objLeadData->table, $objLeadData->join, $objLeadData->where, '', '', '');
//          echopre($leads);
        //return $leads->records;
        return $leads;
    }

    public static function getAllMemebersCommunity($communityAlias, $pagenum = 1, $itemperpage, $search = '') {

        $db = new Db();

        $files = Utils::setTablePrefix('files');

        $users = Utils::setTablePrefix('users');

        $members = Utils::setTablePrefix('community_member');

        $community = Utils::setTablePrefix('communities');
        $userWhere = "m.cmember_status = 'A' AND c.community_alias = '" . $db->escapeString($communityAlias) . "' AND u.user_status='A'";

        if ($search) {
            $userWhere.="AND (CONCAT(u.user_firstname,u.user_lastname) LIKE  '%$search%' OR u.user_email LIKE '%$search%') ";
        }


        $objLeadData = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key = 'm.cmember_id';
        $objLeadData->fields = 'c.*,f.*,u.*,m.*';
        $objLeadData->join = "LEFT JOIN  $members m ON m.cmember_community_id = c.community_id  LEFT JOIN $users u ON m.cmember_id = u.user_id  LEFT JOIN $files f ON u.user_image_id = f.file_id ";
        $objLeadData->where = "$userWhere ";
        //   echo $objLeadData->where;


        $objLeadData->groupbyfield = 'u.user_id';
        $objLeadData->orderby = '';
        $objLeadData->orderfield = '';

        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
//          echopre($leads);
        //return $leads->records;
        return $leads;
    }

    public static function getCommunityImages($communityId,$orderfield='community_id',$orderby='DESC',$pagenum=1,$itemperpage=5) {
        $db = new Db();
        $files                      =   Utils::setTablePrefix('community_announcements');
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'community_announcements';
        $objLeadData->key           = 'community_id';
        $objLeadData->fields	    = '*';
        $objLeadData->where	    = "community_id = '" . $db->escapeString($communityId) . "' AND community_announcement_status = 'A'";
        $objLeadData->orderby	    = $orderby;
        $objLeadData->orderfield    = $orderfield;
        $objLeadData->itemperpage   = $itemperpage;
        $objLeadData->page	    = $pagenum;		// by default its 1
        $objLeadData->debug	    = true;
        $leads                      = $db->getData($objLeadData);
        return $leads;        
    }    
    
    public static function setpermissionsinv($communityid = '', $inv_check = '') {
        //echo $communityid;
        //echopre1($inv_check);
//     	error_reporting(E_ALL);
//     	ini_set('display_errors', 1);

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $db = new Db();
        $community = Utils::setTablePrefix('communities');
        $members = Utils::setTablePrefix('community_member');
        $users = Utils::setTablePrefix('users');
        if ($id == '') {
            $userId = Utils::getAuth('user_id');
        } else {
            $userId = $id;
        }

        foreach ($inv_check as $key => $value) {
            $data = array();
            if ($value == 0) {
                $data['cmember_inv_permission'] = 'N';
            } else {
                $data['cmember_inv_permission'] = 'Y';
            }
            $where = "cmember_community_id = " . $communityid . " AND cmember_id = " . $key . "";
            $cmemberlistid = $db->update($members, $data, $where, $doAudit = false);
        }

        //Logger::info($objResult);
        return $objResult->status;
    }

    public static function getCommunityMembers($alias = '', $status = 'A', $perPage = 5, $orderfield='community_id',$orderby='DESC',$pagenum=1) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($alias != '') {
            $db = new Db();
            $tableName = 'communities';


            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');

            $members = Utils::setTablePrefix('community_member');
            $limit = '';
            if ($perPage) {
                //$limit = "LIMIT 0,$perPage";
                $limit_start = 0;
                if($pagenum>1){
                    $limit_start = (($pagenum-1)*$perPage);
                }
                $limit = "ORDER BY $orderfield $orderby LIMIT $limit_start,$perPage";
            }
            //echo is_int($alias);
            if (is_numeric($alias)) {

                $query = "SELECT  c.*, u.*, f.*,m.* FROM $community c LEFT JOIN $members m ON c.community_id = m.cmember_community_id LEFT JOIN $users u ON m.cmember_id = u.user_id  LEFT JOIN $files f ON u.user_image_id = f.file_id WHERE c.community_id = '" . $db->escapeString($db->escapeString($alias)) . "' AND m.cmember_status = '" . $db->escapeString($status) . "' AND u.user_status = 'A' $limit";
                 //echo $query;

                $countQuery = "SELECT  c.*, u.*, f.*,m.* FROM $community c LEFT JOIN $members m ON c.community_id = m.cmember_community_id LEFT JOIN $users u ON m.cmember_id = u.user_id  LEFT JOIN $files f ON u.user_image_id = f.file_id WHERE c.community_id = '" . $db->escapeString($db->escapeString($alias)) . "' AND m.cmember_status = '" . $db->escapeString($status) . "' AND u.user_status = 'A' ";
            } else {
                $query = "SELECT  c.*, u.*, f.*,m.* FROM $community c LEFT JOIN $members m ON c.community_id = m.cmember_community_id LEFT JOIN $users u ON m.cmember_id = u.user_id  LEFT JOIN $files f ON u.user_image_id = f.file_id WHERE c.community_alias = '" . $db->escapeString($db->escapeString($alias)) . "' AND m.cmember_status = '" . $db->escapeString($status) . "' AND u.user_status = 'A' $limit";
//                 echo $query;

                $countQuery = "SELECT  c.*, u.*, f.*,m.* FROM $community c LEFT JOIN $members m ON c.community_id = m.cmember_community_id LEFT JOIN $users u ON m.cmember_id = u.user_id  LEFT JOIN $files f ON u.user_image_id = f.file_id WHERE c.community_alias = '" . $db->escapeString($db->escapeString($alias)) . "' AND m.cmember_status = '" . $db->escapeString($status) . "' AND u.user_status = 'A' ";
            }

//echo $countQuery;exit;
            $count = count($db->selectQuery($countQuery));


            Logger::info($query);

            $objResultRow = $db->selectQuery($query);
            
if($perPage != 3){
            // print_r($objResultRow);
            $objResult->memberCount = ($count) ? $count : 0;
            // If community exists then assign community data to result object
            if (count($objResultRow) > 0) {
                $objResult->data = $objResultRow; // Assign community record  to object
            } else {
                $objResult->status = "ERROR";
                $objResult->message = COMMUNITY_ID_NOT_EXIST; // User not exists
            }
}else{
      $objResult = $objResultRow;
}
        }

        Logger::info($objResult);
        return $objResult;
    }

    public static function chekMemeber($userId, $communityId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($userId != '') {
            $db = new Db();
            $tableName = 'community_member';
            $selectCase = 'cmember_id =' . $db->escapeString($userId) . ' AND cmember_community_id =' . $db->escapeString($communityId) . ' AND (cmember_status = "A" OR cmember_status = "I") ';
            Logger::info($selectCase);

            $objResultRow = $db->selectRecord($tableName, '*', $selectCase);
            // If community exists then assign community data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    public static function getFriendList($communityId, $userId) {

        $objResult = new Messages();
        $objResult->status = SUCCESS;

        if ($userId != '') {

            $db = new Db();
            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');

            $members = Utils::setTablePrefix('community_member');

            $invite = Utils::setTablePrefix('invitation');


            $friends = Utils::setTablePrefix('friends_list');

            $query = "SELECT f.*,u.*,fl.* FROM $friends f INNER JOIN $users u ON u.user_id = f.friends_list_friend_id LEFT JOIN $files fl ON u.user_image_id = fl.file_id  WHERE f.friends_list_user_id = '" . $userId . "' AND u.user_id NOT IN(select cmember_id from $members where cmember_community_id = '" . $communityId . "') AND u.user_id NOT IN(select invitation_receiver_id from $invite where invitation_entity_id = '" . $communityId . "' AND invitation_entity = 'C' AND (invitation_status='A' OR invitation_status='P')) GROUP BY u.user_id";

//                 echo $query;
            Logger::info($query);

            $objResultRow = $db->selectQuery($query);
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
    }

    public static function updateCommunityCounts($id = '') {

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $db = new Db();
        $community = Utils::setTablePrefix('communities');
        $members = Utils::setTablePrefix('community_member');
        $users = Utils::setTablePrefix('users');
        if ($id == '') {
            $userId = Utils::getAuth('user_id');
        } else {
            $userId = $id;
        }


        $query = "SELECT count(*) AS  c from $members  AS m INNER JOIN $community AS cm ON m.cmember_community_id = cm.community_id WHERE m.cmember_id = '" . $userId . "' AND m.cmember_status = 'A' AND cm.community_status!='D'";

        Logger::info($query);
        $objResultRow = $db->selectQuery($query);
        $count = ($objResultRow[0]->c) ? $objResultRow[0]->c : 0;
        $data = array();
        $data['user_community_count'] = $count;
        $where = "user_id = " . $db->escapeString($userId) . " ";
        $customerId = $db->update($users, $data, $where, $doAudit = false);
    }

    public static function updateStatusDelete($communityId = '') {
        $objResult              = new Messages();
        $objResult->status      = SUCCESS;
        if ($communityId == '') {
            $objResult->status  = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Email Alreday Exists
        }
        // Update Community data to  Community table
        if ($objResult->status == SUCCESS) {
            $db                 = new Db();
            $tableName          = Utils::setTablePrefix('communities');
            $where              = "community_id = " . $db->escapeString($communityId) . " ";
            $data               = array('community_status' => 'D');
            $customerId         = $db->update($tableName, $data, $where, $doAudit = false);
            $objResult->data    = $data;
        }
        Logger::info($objResult);
        return $objResult;
    }

    public static function getNonBizcomMembers($communityAlias, $pagenum = 1, $itemperpage, $search = '') {
        $db             = new Db();
        $files          = Utils::setTablePrefix('files');
        $users          = Utils::setTablePrefix('users');
        $members        = Utils::setTablePrefix('community_member');
        $community      = Utils::setTablePrefix('communities');
        if ($search) {
            $searchWhere.="AND (CONCAT(u.user_firstname,u.user_lastname) LIKE  '%$search%' OR u.user_email LIKE '%$search%') ";
        }
        $userWhere      = "u.user_id NOT IN(SELECT 	m.cmember_id 
                            FROM $members m
                            LEFT JOIN $community c ON m.cmember_community_id = c.community_id 
                            WHERE c.community_alias= '" . $db->escapeString($communityAlias) . "' AND m.cmember_status ='A') AND u.user_status = 'A' $searchWhere";
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'users AS u';
        $objLeadData->key           = 'u.user_id';
        $objLeadData->fields        = 'u.*,fl.*';
        $objLeadData->join          = " LEFT JOIN $files fl ON u.user_image_id = fl.file_id";
        $objLeadData->where         = "$userWhere ";
        $objLeadData->groupbyfield  = 'u.user_id';
        $objLeadData->orderby       = '';
        $objLeadData->orderfield    = '';
        $objLeadData->itemperpage   = $itemperpage;
        $objLeadData->page          = $pagenum;  // by default its 1
        $objLeadData->debug         = true;
        $leads                      = $db->getData($objLeadData);
        return $leads;
    }

    public static function getAllCommunities($pagenum = 1, $itemperpage = 10, $search = '') {
        $db                 = new Db();
        $userId             = Utils::getAuth('user_id');
        $files              = Utils::setTablePrefix('files');
        $users              = Utils::setTablePrefix('users');
        $members            = Utils::setTablePrefix('community_member');
          $business = Utils::setTablePrefix('businesses');
        $userWhere          = "(m.cmember_id = '" . $userId . "'   AND c.community_status != 'D') AND (c.community_status = 'A') AND  m.cmember_status = 'A'";
        $objLeadData        = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key   = 'c.community_id';
        $objLeadData->fields = 'c.*,f.*,u.*,count(m.cmember_list_id) As memberCount ';
        $objLeadData->join  = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id "
                . "LEFT JOIN $users as u ON c.community_created_by = u.user_id "
                . "LEFT JOIN $members m ON c.community_id = m.cmember_community_id "
                . " LEFT JOIN $business b ON b.business_id=c.community_business_id ";
        $objLeadData->where = "$userWhere ";
        if ($search != '') {
            $objLeadData->where .= " AND (community_name LIKE  '%$search%')";
        }
        $objLeadData->groupbyfield = 'c.community_id';
        $objLeadData->orderby      = 'ASC';
        $objLeadData->orderfield   = 'community_name';
        $objLeadData->itemperpage  = $itemperpage;
        $objLeadData->page         = $pagenum;  // by default its 1
        $objLeadData->debug        = true;
        $leads                     = $db->getData($objLeadData);
        return $leads;
    }

    
    public static function getCommunityName($id) {
        $objResult                   = new Messages();
        $objResult->status           = SUCCESS;
        if ($id != '') {
            $db                     = new Db();
            $business               = Utils::setTablePrefix('communities');
            $query                  = "SELECT community_name from $business WHERE community_id ='" . $db->escapeString($id) . "' ";
            Logger::info($query);
            $objResultRow           = $db->fetchSingleRow($query);
            //echopre($objResultRow);
            if ($objResultRow)
                $objResult->data    = $objResultRow;
            else {
                $objResult->status  = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST;
            }
        }
        Logger::info($objResult);
        //echopre($objResult);
        return $objResult;
    }

    public function sendPifMail($introductionId, $memberType, $selectedMemberArray, $mailArray, $communityAlias, $mailSubject, $mailSubheading, $mailBody, $mailSpecifiedContact, $mailUnspecifiedContact) {
        $db                         = new Db();
        $objMailer                  = new Mailer();
        $communityDetail            = Communities::getCommunityId($communityAlias);
        //echopre($communityDetail);
        $communityId                = $communityDetail->data->community_id;
        $introductionDetails        =  Connections::getIntroductionDetails($introductionId);
        $userId                     = Utils::getAuth('user_id');
        $user_email                 = Utils::getAuth('user_email');
        $username               = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
        $useralias                  = Utils::getAuth('user_alias');
        if ($memberType == 4) {//BizCom
            foreach ($selectedMemberArray As $selectedMember) {
                $users              = Utils::setTablePrefix('users');
                $communityMember    = Utils::setTablePrefix('community_member');
                $query              = "SELECT  c.cmember_id,u.user_firstname,u.user_lastname,u.user_email  
                                        FROM $communityMember c  
                                        LEFT JOIN $users u ON c.cmember_id = u.user_id  
                                        WHERE c.cmember_status = 'A' AND u.user_status='A'  
                                        AND cmember_community_id=" . $selectedMember;
                Logger::info($query);
                $objResultRow       = $db->fetchAll($db->execute($query));
                foreach ($objResultRow AS $row) {
                    $data           = array();
                    $data           = array(
                                        'introduction_id'       => $introductionId,
                                        'campaign_id'           => $introductionDetails->data->campaign_id,
                                        'pif_from_user_id'      => $userId,
                                        'pif_from_user_email'   => $user_email,
                                        'pif_to_user_id'        => $row->cmember_id,
                                        'pif_to_user_email'     => $row->user_email,
                                        'pif_community_alias'   => $communityAlias,
                                        'pif_community_id'      => $communityId,
                                        'pif_member_type'       => $memberType,
                                        'pif_sent_date'         => date('Y-m-d H:i:s'),
                                        'pif_status'            => 'S'
                                    );
                    $tableName      = Utils::setTablePrefix('pif');
                    $pifId          = $db->insert($tableName, $data);
                    $mailContent    = '<h3>' . $mailSubheading . '</h3>';
                    $mailContent    .= $mailBody;
                    $mailContent    .='<p><a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/join-community/1" target="_blank"> Accept</a> Invitation  OR <a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/reject/1" target="_blank"> Decline</a> Invitation<br><br>'
                                        . 'Sender Name : <a href="'.BASE_URL.'timeline/'.$useralias.'">'.$username.'</a> <br><br>Regards,<br>BBF Team</p>';
                   // echo $mailContent;exit;
                    $mail           = $objMailer->sendIntroductionMail($objResultRow->user_email, $objResultRow->user_firstname, $mailSubject, $mailContent);
                }
            }
        } elseif ($memberType == 5) {//Emails
            foreach ($mailArray As $mail) {
                   $user = User::getUserEmailDetails($mail);
                 //  echo $user->user_id;exit;
                   if($user->user_id > 0){
                     $to_userId = $user->user_id;  
                   }
                   else{
                     $to_userId = ''; 
                   }
                   
                $data                   = array();
                $data                   = array(
                                            'introduction_id'       => $introductionId,
                                            'campaign_id'           => $introductionDetails->data->campaign_id,
                                            'pif_from_user_id'      => $userId,
                                            'pif_from_user_email'   => $user_email,
                                            'pif_to_user_id'        => $to_userId,
                                            'pif_to_user_email'     => $mail,
                                            'pif_community_alias'   => $communityAlias,
                                            'pif_community_id'      => $communityId,
                                            'pif_member_type'       => $memberType,
                                            'pif_sent_date'         => date('Y-m-d H:i:s'),
                                            'pif_status'            => 'S'
                                        );
                $tableName           = Utils::setTablePrefix('pif');
                $pifId               = $db->insert($tableName, $data);
                $mailContent         = '<h3>' . $mailSubheading . '</h3>';
                $mailContent        .= $mailBody;
                $mailContent        .='<p><a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/join-community/1" target="_blank"> Accept</a> Invitation  OR <a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/reject/1" target="_blank"> Decline</a> Invitation<br><br>'
                                    . 'Sender Name : <a href="'.BASE_URL.'timeline/'.$useralias.'">'.$username.'</a><br><br>Regards,<br>BBF Team</p>';
                $mail               = $objMailer->sendIntroductionMail($mail, $objResultRow->user_firstname, $mailSubject, $mailContent);
            }
        } else {
            //echopre1($selectedMemberArray);
            foreach ($selectedMemberArray As $selectedMember) {
                $selectCase         = '  user_id =' . $selectedMember;
                Logger::info($selectCase);
                $objResultRow       = $db->selectRecord('users', '*', $selectCase);
                $data               = array();
                $data               = array(
                                        'introduction_id'       => $introductionId,
                                        'campaign_id'           => $introductionDetails->data->campaign_id,
                                        'pif_from_user_id'      => $userId,
                                        'pif_from_user_email'   => $user_email,
                                        'pif_to_user_id'        => $selectedMember,
                                        'pif_to_user_email'     => $objResultRow->user_email,
                                        'pif_community_alias'   => $communityAlias,
                                        'pif_community_id'      => $communityId,
                                        'pif_member_type'       => $memberType,
                                        'pif_sent_date'         => date('Y-m-d H:i:s'),
                                        'pif_status'            => 'S'
                                    );
                $tableName          = Utils::setTablePrefix('pif');
                $pifId              = $db->insert($tableName, $data);
                $mailContent        = '<h3>' . $mailSubheading . '</h3>';
                $mailContent        .= $mailBody;
                $mailContent        .='<p><a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/join-community/1" target="_blank"> Accept</a> Invitation  OR <a href="' . BASE_URL . 'accept-pif-invitation/' . $pifId . '/reject/1" target="_blank"> Decline</a> Invitation<br><br>'
                                    . 'Sender Name : <a href="'.BASE_URL.'timeline/'.$useralias.'">'.$username.'</a><br><br>Regards,<br>BBF Team</p>';
                $mail               = $objMailer->sendIntroductionMail($objResultRow->user_email, $objResultRow->user_firstname, $mailSubject, $mailContent);
            }
        }
            self::updateNumPifSent($introductionId);
        
    }
    
    public static function updateNumPifSent($introductionId) {
        $db                 = new Db();
        $pif                = Utils::setTablePrefix('pif');
        $query              = "SELECT count(pif_id) AS NumPif from $pif P 
                                       WHERE introduction_id ='" . $db->escapeString($introductionId) . "' ";
        Logger::info($query);
        $objResultRow       = $db->fetchSingleRow($query);
        $fielddata          = array();
        $fielddata          = array(
                                'introduction_num_pif_sent' => $objResultRow->NumPif,
                                'introduction_pif_approval_status'=>P
                            );
        $tableName          = Utils::setTablePrefix('initiate_introductions');
        $where              = 'introduction_id=' . $introductionId;
        return $campaignId = $db->update($tableName, $fielddata, $where);
    }

    public static function getCommunityOwnerDetails($id) {
        $objResult                  = new Messages();
        $objResult->status          = SUCCESS;
        if ($id != '') {
            $db = new Db();
            $communityMember        = Utils::setTablePrefix('community_member');
            $user                   = Utils::setTablePrefix('users');
            $query                  = "SELECT u.* from $communityMember cm 
                                        LEFT JOIN $user u ON u.user_id= cm.cmember_id
                                        WHERE 	cmember_community_id ='" . $db->escapeString($id) . "' 
                                        AND cmember_type ='A'";
            Logger::info($query);
            $objResultRow           = $db->fetchSingleRow($query);
            if ($objResultRow)
                $objResult->data    = $objResultRow;
            else {
                $objResult->status  = "ERROR";
                $objResult->message = USER_ID_NOT_EXIST;
            }
        }
        Logger::info($objResult);
        //echopre($objResult);
        return $objResult;
    }
     public static function getMyCommunitiesPendingMembers($pagenum = 1, $itemperpage = 10, $search = '') {
        $db                     = new Db();
        $userId                 = Utils::getAuth('user_id');
        $files                  = Utils::setTablePrefix('files');
        $users                  = Utils::setTablePrefix('users');
        $communities            = Utils::setTablePrefix('communities');
        $communityMembers       = Utils::setTablePrefix('community_member');
        $userWhere              = "(m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D') OR(c.community_status = 'A' AND community_type = 'PUBLIC' ) ";
        $userWhere              = "  c.community_id IN (SELECT community_id 
                                    FROM $communities cc
                                    LEFT JOIN $communityMembers ccm ON ccm.cmember_community_id=cc.community_id 
                                    WHERE  ccm.cmember_type='A' AND ccm.cmember_id=$userId) 
                                    AND cm.cmember_status ='I' 
                                    AND cm.cmember_pif_id >0 
                                    AND c.community_status != 'D'";
        $objLeadData            = new stdClass();
        $objLeadData->table     = 'community_member AS cm';
        $objLeadData->key       = 'c.community_id';
        $objLeadData->fields    = 'u.*,f.*,c.*';
        $objLeadData->join      = "LEFT JOIN  $communities c ON c.community_id =cm.cmember_community_id 
                                LEFT JOIN $users u ON u.user_id=cm.cmember_id 
                                LEFT JOIN $files f ON f.file_id=c.community_image_id ";
        $objLeadData->where     = "$userWhere ";
        if ($search != '') {
            $objLeadData->where .= " AND (c.community_name LIKE  '%$search%' OR u.user_firstname LIKE '%$search%' )";
        }
        $objLeadData->groupbyfield  = '';
        $objLeadData->orderby       = 'ASC';
        $objLeadData->orderfield    = 'c.community_name';
        $objLeadData->itemperpage   = $itemperpage;
        $objLeadData->page          = $pagenum;  // by default its 1
        $objLeadData->debug         = true;
       // echopre($objLeadData);
        $leads                      = $db->getData($objLeadData);
        return $leads;
    }
    
    public static function getMyCommunitiesPendingMembersJoin($pagenum = 1, $itemperpage = 10, $search = '') {
        $db                     = new Db();
        $userId                 = Utils::getAuth('user_id');
        $files                  = Utils::setTablePrefix('files');
        $users                  = Utils::setTablePrefix('users');
        $communities            = Utils::setTablePrefix('communities');
        $communityMembers       = Utils::setTablePrefix('community_member');
        //$users                      = Utils::setTablePrefix('users');
          $where                          = '  user_id =' . $db->escapeString($db->escapeString($userId));
            $frndcount                 = 0;
            $db->update($users, array('user_private_request_count' => $frndcount), $where, $doAudit = false);
        $userWhere              = "(m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A' AND c.community_status != 'D') OR(c.community_status = 'A' AND community_type = 'PUBLIC' ) ";
        $userWhere              = "  c.community_id IN (SELECT community_id 
                                    FROM $communities cc
                                    LEFT JOIN $communityMembers ccm ON ccm.cmember_community_id=cc.community_id 
                                    WHERE  ccm.cmember_type='A' AND ccm.cmember_id=$userId) 
                                    AND cm.cmember_status ='P' 
                                    AND cm.cmember_pif_id =0 
                                    AND c.community_status != 'D'";
        $objLeadData            = new stdClass();
        $objLeadData->table     = 'community_member AS cm';
        $objLeadData->key       = 'c.community_id';
        $objLeadData->fields    = 'u.*,f.*,c.*';
        $objLeadData->join      = "LEFT JOIN  $communities c ON c.community_id =cm.cmember_community_id 
                                LEFT JOIN $users u ON u.user_id=cm.cmember_id 
                                LEFT JOIN $files f ON f.file_id=u.user_image_id ";
        $objLeadData->where     = "$userWhere ";
        if ($search != '') {
            $objLeadData->where .= " AND (c.community_name LIKE  '%$search%' OR u.user_firstname LIKE '%$search%' )";
        }
        $objLeadData->groupbyfield  = '';
        $objLeadData->orderby       = 'ASC';
        $objLeadData->orderfield    = 'c.community_name';
        $objLeadData->itemperpage   = $itemperpage;
        $objLeadData->page          = $pagenum;  // by default its 1
        $objLeadData->debug         = true;
       // echopre($objLeadData);
        $leads                      = $db->getData($objLeadData);
        return $leads;
    }
    
     public static function getMyCommunityMembers($userid, $pagenum = 1, $itemperpage, $search = '') {

        $db = new Db();
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');
        $members = Utils::setTablePrefix('community_member');
        $community = Utils::setTablePrefix('communities');
        //$userWhere = "m.cmember_status = 'A' AND c.community_alias = '" . $db->escapeString($communityAlias) . "' AND u.user_status='A'";
        $userWhere = " C.community_id IN (SELECT cmember_community_id FROM $members 
                        WHERE cmember_id=$userid AND cmember_type='A' ) AND cmember_type='U' AND U.user_id is not null";

        if ($search) {
            $userWhere.=" AND (CONCAT(U.user_firstname,U.user_lastname) LIKE  '%$search%' OR U.user_firstname LIKE '%$search%'  OR U.user_lastname LIKE '%$search%') ";
        }


        $objLeadData = new stdClass();
        $objLeadData->table = 'community_member CM ';
        $objLeadData->key = 'U.user_id';
        $objLeadData->fields = 'distinct(U.user_id),U.*,f.*';
        $objLeadData->join = "Left join $community C ON C.community_id=CM.cmember_community_id AND C.community_status='A' AND C.community_created_by = $userid
                              Left join $users U ON  U.user_id=CM.cmember_id AND CM.cmember_status='A' AND U.user_status='A' 
                              LEFT JOIN $files f ON U.user_image_id = f.file_id ";
        $objLeadData->where = "$userWhere ";
        //   echo $objLeadData->where;


        $objLeadData->groupbyfield = 'U.user_id';
        $objLeadData->orderby = '';
        $objLeadData->orderfield = '';

        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
        // echopre1($leads);
        //return $leads->records;
        return $leads;
    }
     public static function getMyNonCommunityMembers($userid, $pagenum = 1, $itemperpage, $search = '') {

        $db                 = new Db();
        $files              = Utils::setTablePrefix('files');
        $users              = Utils::setTablePrefix('users');
        $members            = Utils::setTablePrefix('community_member');
        $community          = Utils::setTablePrefix('communities');
        //$userWhere = "m.cmember_status = 'A' AND c.community_alias = '" . $db->escapeString($communityAlias) . "' AND u.user_status='A'";
        $userWhere          = " U.user_id NOT IN(Select distinct(U.user_id) from $members CM  
                                Left join $community C ON C.community_id=CM.cmember_community_id AND C.community_status='A' 
                                Left join $users U ON  U.user_id=CM.cmember_id AND CM.cmember_status='A' AND U.user_status='A' 
                                WHERE C.community_id IN (SELECT cmember_community_id FROM $members 
                                WHERE cmember_id=$userid AND cmember_type='A' ) AND U.user_id is not null) 
                                AND U.user_status='A' ";

        if ($search) {
            $userWhere.=" AND (CONCAT(U.user_firstname,U.user_lastname) LIKE  '%$search%' OR U.user_firstname LIKE '%$search%' OR U.user_lastname LIKE '%$search%' ) ";
        }
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'users U ';
        $objLeadData->key           = 'U.user_id';
        $objLeadData->fields        = 'distinct(U.user_id),U.*,f.*';
        $objLeadData->join          = "LEFT JOIN  $files f ON U.user_image_id = f.file_id  ";
        $objLeadData->where         = "$userWhere ";
        $objLeadData->groupbyfield = 'U.user_id';
        $objLeadData->orderby      = '';
        $objLeadData->orderfield   = '';
        $objLeadData->itemperpage  = $itemperpage;
        $objLeadData->page        = $pagenum;  // by default its 1
        $objLeadData->debug       = true;
        $leads                    = $db->getData($objLeadData);
        return $leads;
    }
    
    
    
   
    
    public static function getBusinessIdFromBizcom($bizcomId){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT community_business_id FROM ".$tableName. " WHERE community_id=".$bizcomId;
        $objResultRow                   = $db->fetchSingleRow($query);
        return $objResultRow->community_business_id;
    }
    
    public static function getAnnouncements($communityId,$pagenum='',$itemperpage=''){
        $db                             = new Db();
        $userId                 = Utils::getAuth('user_id');
        if($userId){
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $tableName1                      = Utils::setTablePrefix('files');
        $tableName2                     = Utils::setTablePrefix('communities');
        $tableName3                     = Utils::setTablePrefix('community_member');
        $tableName4                     = Utils::setTablePrefix('announcement_comments');
        $tableName5                     = Utils::setTablePrefix('users');
        $date = date('Y-m-d h:m:s');
        
         if($itemperpage) 	$itemPerPage 	= $itemperpage;
 		else 						$itemPerPage 	= PAGE_LIST_COUNT;
// 		
 		if($pagenum) 			$currentPage 	= $pagenum;
 		else 						$currentPage 	= '1';
// 		$totPages 					= ceil($totRecords/$itemPerPage);
// 		$objRes->totpages 			= $totPages;
// 		$objRes->currentpage 		= $currentPage;

 		// get the limit of the query
                if($pagenum){
 		$limitStart = ($currentPage * $itemPerPage) - $itemPerPage;
 		$limitEnd 	= $itemPerPage;
 		$limitVal 	= ' LIMIT '.$limitStart.','.$limitEnd;
                }
                else{
                    $limitVal ='';
                }
       
        $where                       = '  cmember_id =' . $db->escapeString($userId).' AND cmember_community_id='.$communityId;
            $ancmntcount                 = 0;
            $db->update($tableName3, array('cmember_announcement_count' => $ancmntcount), $where, $doAudit = false);

        
        $likes                      = Utils::setTablePrefix('announcement_likes');
        $query                          = "SELECT C.*,U.user_firstname,U.user_lastname,U.user_alias,DATEDIFF('$date',C.community_announcement_date) as days,F.file_path,"
                . "(SELECT COUNT(announcement_like_id) from $likes l WHERE l.announcement_like = '1' "
                . "AND l.announcement_id = C.community_announcement_id)AS Count,CM.community_business_id FROM ".$tableName." AS C "
             
                . "LEFT JOIN ".$tableName2." AS CM ON CM.community_id = C.community_id "
                . "LEFT JOIN ".$tableName5." AS U ON U.user_id = C.community_announcement_user_id LEFT JOIN ".$tableName1." AS F ON F.file_id = U.user_image_id  WHERE C.community_id=".$communityId." "
                . "AND C.community_announcement_status !='D' ORDER BY C.community_announcement_date DESC $limitVal";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        return $objResultRow;
        }
    }
    
    
    public static function getAnnouncementsNewsfeed($pagenum='',$itemperpage='',$userId = ''){
        $db                             = new Db();
        $userId                 = $userId;
        if($userId){
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $tableName1                      = Utils::setTablePrefix('files');
        $tableName2                     = Utils::setTablePrefix('communities');
        $tableName3                     = Utils::setTablePrefix('community_member');
        $tableName4                     = Utils::setTablePrefix('announcement_comments');
        $tableName5                     = Utils::setTablePrefix('users');
        $date = date('Y-m-d h:m:s');
        
         if($itemperpage) 	$itemPerPage 	= $itemperpage;
 		else 						$itemPerPage 	= PAGE_LIST_COUNT;
// 		
 		if($pagenum) 			$currentPage 	= $pagenum;
 		else 						$currentPage 	= '1';
// 		$totPages 					= ceil($totRecords/$itemPerPage);
// 		$objRes->totpages 			= $totPages;
// 		$objRes->currentpage 		= $currentPage;

 		// get the limit of the query
                if($pagenum){
 		$limitStart = ($currentPage * $itemPerPage) - $itemPerPage;
 		$limitEnd 	= $itemPerPage;
 		$limitVal 	= ' LIMIT '.$limitStart.','.$limitEnd;
                }
                else{
                    $limitVal ='';
                }
       
        $where                       = '  cmember_id =' . $db->escapeString($userId);
            $ancmntcount                 = 0;
            $db->update($tableName3, array('cmember_announcement_count' => $ancmntcount), $where, $doAudit = false);

        
        $likes                      = Utils::setTablePrefix('announcement_likes');
        $query                          = "SELECT C.*,U.user_firstname,U.user_lastname,U.user_alias,DATEDIFF('$date',C.community_announcement_date) as days,F.file_path as User_Image,"
                . "(SELECT COUNT(announcement_like_id) from $likes l WHERE l.announcement_like = '1' "
                . "AND l.announcement_id = C.community_announcement_id)AS Count,CM.community_business_id FROM ".$tableName." AS C "
                . "LEFT JOIN ".$tableName2." AS CM ON CM.community_id = C.community_id "
                . "LEFT JOIN ".$tableName5." AS U ON U.user_id = C.community_announcement_user_id LEFT JOIN ".$tableName1." AS F ON F.file_id = U.user_image_id  WHERE C.community_id IN(SELECT cmember_community_id FROM $tableName3 WHERE cmember_id= $userId) "
                . "AND C.community_announcement_status !='D' AND CM.community_status !='D' ORDER BY C.community_announcement_date DESC $limitVal";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        return $objResultRow;
        }
    }
    
    public static function getAnnouncementsCount($communityId){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $query                          = "SELECT community_announcement_id FROM ".$tableName." WHERE community_id=".$communityId;
        $objResultRow                   = $db->fetchAll($db->execute($query));
        return $objResultRow;
    }
    
    public static function addAnnouncements($announcmentArr){
        //echopre1($announcmentArr);
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $tableName1                     = Utils::setTablePrefix('community_member');
        $msg                            = array();
            	try {
                    $excludeId = '';
             $AnnouncementAliasName         = Utils::generateAlias($tableName, $announcmentArr['community_announcement_title'], $idColumn = "community_announcement_id", $id = $excludeId, $aliasColumn = "community_announcement_alias");

            $fileHandler                = new Filehandler();
            $emailLogoFileDetails       = $fileHandler->handleUpload($_FILES['file']);
            $image_id                   = $emailLogoFileDetails->file_id;
            $image                      = $emailLogoFileDetails->file_path;
            move_uploaded_file($image,FILE_UPLOAD_DIR);
            //Utils::allResize($image, 'medium', 697, 205);
            //Utils::allResize($image, 'small', 75, 75);
            //Utils::allResize($image, 'thumb', 50, 50);
//            $dataArray['user_image_name']   = $image;
//            $dataArray['user_image_id']     = $image_id;
           // $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'user_id="' . $db->escapeString($objUserImageData->user_id) . '"');
           // $msg['msg']                     = PROFILE_PIC_CHANGED;
            //$msg['msgcls']                  = 'success_div';
            $msg['file']                    = $image;
            $data                           = array();
            $announcmentArr['community_announcement_image_id']          = $image_id;
            $announcmentArr['community_announcement_image_path']          = $image;
            $announcmentArr['community_announcement_alias']          = $AnnouncementAliasName;
            //$data['announcement_image_status']          = 'I';
//            $data['announcement_image_date']          = $objUserImageData->announcement_image_date;
//echopre($data);exit;
           // $announcement_comment_image_id                     = $db->insert($tableName, $data);
            
       
        } 
        catch(Exception $e){
    		$msg['msg']             = $e->getMessage();
    		$msg['msgcls']          = 'error_div';
               // $msg['image_id']          = $announcement_comment_image_id;
    	}
         $result                                             = self::getCommunityAlias( $announcmentArr['community_id']);
        $alias           = $result->data->community_alias;
        $members                                            = self::getAllMemebersCommunity($alias, 1, 9);
        //echopre1($members);
        foreach($members->records as $data){
            $where                       = '  cmember_id =' . $db->escapeString($data->cmember_id).' AND cmember_community_id='.$announcmentArr['community_id'];
            $ancmntcount                 = $db->selectRow('community_member', 'cmember_announcement_count', $where);
            $ancmntcount++;
            $db->update($tableName1, array('cmember_announcement_count' => $ancmntcount), $where, $doAudit = false);
  
        }
        //$msg['image_id']          = $announcement_comment_image_id;
      //  return $msg;
     //  echopre($announcmentArr);
        $res                            = $db->insert($tableName, $announcmentArr);
        return $image."@".$res;
    }
    
    public static function deleteAnnouncements($announcmentId){
        $db                             = new Db();
       
        $res                            = $db->deleteRecord("community_announcements","community_announcement_id=".$announcmentId);
        
        return $res;
    }
    
    public static function editAnnouncements($announcmentId){
        $db                             = new Db();
        
        $res                            = $db->selectRecord("community_announcements","*","community_announcement_id=".$announcmentId);
        
        return $res;
    }
    
    public static function updateAnnouncements($announcmentArr,$announcmentId){
        $db                             = new Db();
        //echopre($announcmentArr);
        $image = ' ';
        if($_FILES['file']){
            $fileHandler                = new Filehandler();
            $emailLogoFileDetails       = $fileHandler->handleUpload($_FILES['file']);
            $image_id                   = $emailLogoFileDetails->file_id;
            $image                      = $emailLogoFileDetails->file_path;
            move_uploaded_file($image,FILE_UPLOAD_DIR);
            //Utils::allResize($image, 'medium', 697, 205);
            //Utils::allResize($image, 'small', 75, 75);
            //Utils::allResize($image, 'thumb', 50, 50);
//            $dataArray['user_image_name']   = $image;
//            $dataArray['user_image_id']     = $image_id;
           // $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'user_id="' . $db->escapeString($objUserImageData->user_id) . '"');
           // $msg['msg']                     = PROFILE_PIC_CHANGED;
            //$msg['msgcls']                  = 'success_div';
            $msg['file']                    = $image;
            $data                           = array();
            $announcmentArr['community_announcement_image_id']          = $image_id;
            $announcmentArr['community_announcement_image_path']          = $image;
            //$announcmentArr['community_announcement_alias']          = $AnnouncementAliasName;
        }
        
        $res                            = $db->updateFields("community_announcements", $announcmentArr,"community_announcement_id=".$announcmentId);
        $res = ' ';
        return $image."@".$announcmentId;
    }
    
   
    public static function getAllCommunityByBusiness($orderfield = 'community_name', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '', $userMode = '',$businessid) {
//echo $userId;exit;
        $db = new Db();

        $files = Utils::setTablePrefix('files');

        $users = Utils::setTablePrefix('users');
        $category = Utils::setTablePrefix('categories');

        $members = Utils::setTablePrefix('community_member');
        $business = Utils::setTablePrefix('businesses');

        if ($userId > 0) {
            $where =" c.community_status != 'D'";
            if ($userMode == 'A') {//Admin level check
                $userWhere = " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A'  AND m.cmember_type='A'";
            } 
            //Member level check
            else if ($userMode == 'U') {
                $userWhere = " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A'  AND m.cmember_type='U'" ;
            }
            else {//Both admin and members
                $userWhere = " AND m.cmember_id = '" . $userId . "'  AND m.cmember_status = 'A'" ;
            }
            
        } else {
            $where = "c.community_status != 'D' AND community_type = 'PUBLIC' ";
            $userWhere='';
        }

        $objLeadData = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key = 'c.community_id';
        $objLeadData->fields = "c.*,f.*,u.*,ifnull(b.business_name,'Personal')AS business_name,b.business_category_id,ct.category_name";
        $objLeadData->join = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                                LEFT JOIN $users as u ON c.community_created_by = u.user_id 
                                LEFT JOIN $members m ON c.community_id = m.cmember_community_id $userWhere 
                                LEFT JOIN $business b ON b.business_id=c.community_business_id LEFT JOIN $category AS ct ON ct.category_id = b.business_category_id";
        $objLeadData->where = "$where ";
        //   echo $objLeadData->where;

        if ($search != '') {
            $objLeadData->where .= " AND (";
            $fieldsize = sizeof($searchFieldArray);
            $i = 1;
            foreach ($searchFieldArray AS $searchField) {
                $objLeadData->where .= " $searchField LIKE '%$search%' ";
                if ($i == $fieldsize) {
                    $objLeadData->where .= " )";
                } else {
                    $objLeadData->where .= " OR";
                }
                $i++;
            }
        }
        if($businessid >= 0 && $userId > 0){
            //$objLeadData->where .= " AND c.community_business_id=$businessid AND c.community_created_by = '".$userId."'";
        }
        if($businessid >= 0){
            $objLeadData->where .= " AND c.community_business_id=$businessid ";
        }
        $objLeadData->groupbyfield = 'c.community_id';
        $objLeadData->orderby = $orderby;
        $objLeadData->orderfield = $orderfield;
        $objLeadData->itemperpage = $itemperpage;
        $objLeadData->page = $pagenum;  // by default its 1
        $objLeadData->debug = true;
        $leads = $db->getData($objLeadData);
        return $leads;
    }
    
     public static function getCommunitySuggestions($business_id,$community_id,$page, $perpage) {
       // echo $page;
        // echo "here";exit;
        if(($business_id != '' && $community_id != '')&&($business_id != 0 && $community_id != 0)){
        $limit              =  " " ;  
        $db                     = new Db();
        $userId                 = Utils::getAuth('user_id');
        $files                  = Utils::setTablePrefix('files');
        $community              = Utils::setTablePrefix('communities');
        $communityMembers       = Utils::setTablePrefix('community_member');
        if($page == 0){
            $limit              =  " LIMIT 0 ,2" ;  
        }
        else{
            $limit              =  " " ;  
        }
        $query                  = "SELECT C.*,F.* FROM $community C 
                                    LEFT JOIN $files F ON F.file_id =C.community_image_id 
                                    WHERE C.community_business_id=$business_id 
                                    AND community_id 
                                    NOT IN(SELECT cmember_community_id 
                                    FROM $communityMembers  CM 
                                    LEFT JOIN $community B ON B.community_id = CM.cmember_community_id 
                                    WHERE CM.cmember_id=$userId AND B.community_business_id =$business_id )
                                    AND community_id !=$community_id AND community_status != 'D' $limit 
                                   ";
       
       //echo $query;exit;
        Logger::info($query);
        $objResultRow               = $db->fetchAll($db->execute($query));
       // echopre($objResultRow);
        if ($objResultRow)
            $objResult->data        = $objResultRow;
        else {
            $objResult->status      = "ERROR";
            $objResult->message     = NO_FRIEND_SUGGESTION;
        }
        return $objResult; 
        }
    }
    
     public static function getCommunitySuggestionsWithoutLog($community_alias) {
        $community = Business::getBusinessCommunityAlias($community_alias);
        $business_id =  $community->community_business_id;
       // echopre1($community);
       // echo $page;
        // echo "here";exit;
        $limit              =  " " ;  
        $db                     = new Db();
        $userId                 = Utils::getAuth('user_id');
        $files                  = Utils::setTablePrefix('files');
        $community              = Utils::setTablePrefix('communities');
        $communityMembers       = Utils::setTablePrefix('community_member');
        if($page == 0){
            $limit              =  " LIMIT 0 ,2" ;  
        }
        else{
            $limit              =  " " ;  
        }
        $query                  = "SELECT C.*,F.* FROM $community C 
                                    LEFT JOIN $files F ON F.file_id =C.community_image_id 
                                    WHERE C.community_business_id = $business_id  
                                    AND community_id 
                                    NOT IN(SELECT cmember_community_id 
                                    FROM $communityMembers  CM 
                                    LEFT JOIN $community B ON B.community_id = CM.cmember_community_id 
                                    WHERE B.community_business_id = $business_id )
                                    AND community_alias != '$community_alias' $limit 
                                   ";
      
       // echo $query;exit;
        Logger::info($query);
        $objResultRow               = $db->fetchAll($db->execute($query));
       // echopre($objResultRow);
        if ($objResultRow)
            $objResult->data        = $objResultRow;
        else {
            $objResult->status      = "ERROR";
            $objResult->message     = NO_FRIEND_SUGGESTION;
        }
        return $objResult; 
    }
    
         public static function getCommunitySuggestionsall($business_id,$community_id,$page, $perpage) {
        if($business_id > 0){
        $db                     = new Db();
        $userId                 = Utils::getAuth('user_id');
        $files                  = Utils::setTablePrefix('files');
        $community              = Utils::setTablePrefix('communities');
        $communityMembers       = Utils::setTablePrefix('community_member');
//        if($page == 0){
//            $limit              =  " LIMIT 0 ,2" ;  
//        }
//        else{
//            $limit              =  " " ;  
//        }
       
        $query                  = "SELECT C.*,F.* FROM $community C 
                                    LEFT JOIN $files F ON F.file_id =C.community_image_id 
                                    WHERE C.community_business_id=$business_id 
                                    AND community_id 
                                    NOT IN(SELECT cmember_community_id 
                                    FROM $communityMembers  CM 
                                    LEFT JOIN $community B ON B.community_id = CM.cmember_community_id 
                                    WHERE CM.cmember_id=$userId AND B.community_business_id =$business_id )
                                    AND community_id !=$community_id AND C.community_status != 'D'
                                   ";
      //echo $query; exit;
        Logger::info($query);
        $objResultRow               = $db->fetchAll($db->execute($query));
       // echopre($objResultRow);
        if ($objResultRow){
            $objResult->data        = $objResultRow;
            $objResult->totalrecord = count($objResultRow);
         }
        else {
            $objResult->status      = "ERROR";
            $objResult->message     = NO_FRIEND_SUGGESTION;
        }
        return $objResult->data; 
        }
        else
            return false;
    }
    
   
    public static function getCommunityCount(){
        $db                             = new Db();
        $userId                 = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT COUNT(community_created_by) AS count FROM ". $tableName." WHERE community_created_by = '".$userId."' AND community_status = 'A'";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        $community_count =  $objResultRow[0]->count;
        return $community_count;
    }
    
    public static function getSubscribedCommunityCount(){
        $db                             = new Db();
        $userId                         = Utils::getAuth('user_id');
        $communities                    = Utils::setTablePrefix('communities');
        $users                          = Utils::setTablePrefix('users');
        $community_member               = Utils::setTablePrefix('community_member');
        $businesses                     = Utils::setTablePrefix('businesses');
        $files                          = Utils::setTablePrefix('files');
        $query                          = "SELECT c.*,f.*,u.*,ifnull(b.business_name,'Personal')AS business_name,count(m.cmember_id) AS count FROM $communities AS c LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                                LEFT JOIN $users as u ON c.community_created_by = u.user_id 
                                LEFT JOIN $community_member m ON c.community_id = m.cmember_community_id
                                LEFT JOIN $businesses b ON b.business_id=c.community_business_id WHERE m.cmember_id = '".$userId."'  AND m.cmember_status = 'A' AND c.community_status != 'D' AND m.cmember_type='U'  GROUP BY c.community_id ORDER BY community_id";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        $community_count = count($objResultRow);
        return $community_count;
    }
    
        
    public static function getAnnouncementCount(){
        $db                             = new Db();
        $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $query                          = "SELECT community_announcement_id FROM ".$tableName." WHERE community_announcement_created_by='".$userId."'";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        return $objResultRow;
    }
    
 
    public static function getFilePath($file_id){

    $db                             = new Db();
    $tableName                      = Utils::setTablePrefix('files');
    $query                          = "SELECT file_path from $tableName WHERE file_id = '$file_id'";
    $objResultRow                  = $db->fetchSingleRow($query);
    return $objResultRow;
    }    
    
    public static function getCategoryId($business_id){

    $db                             = new Db();
    $tableName                      = Utils::setTablePrefix('businesses');
    $query                          = "SELECT business_category_id from $tableName WHERE business_id = '$business_id'";
    $objResultRow                  = $db->fetchSingleRow($query);
    return $objResultRow;
    }  
    
    public static function getCommunityNameByAlias($alias){

    $db                             = new Db();
    $tableName                      = Utils::setTablePrefix('communities');
    $query                          = "SELECT community_name from $tableName WHERE community_alias = '$alias'";
    $objResultRow                  = $db->fetchSingleRow($query);
    return $objResultRow;
    }  
    
    public static function getAllCommunitites(){
    $userId                         = Utils::getAuth('user_id');
    $db                             = new Db();
    $tableName                      = Utils::setTablePrefix('communities');
    $files                          = Utils::setTablePrefix('files');
    $users                          = Utils::setTablePrefix('users');
    $community_member               = Utils::setTablePrefix('community_member');
    $businesses                     = Utils::setTablePrefix('businesses');
    $query                          = " SELECT c.*,f.*,u.*,ifnull(b.business_name,'Personal')AS business_name FROM $tableName AS c LEFT JOIN $files AS f ON c.community_image_id= f.file_id 
                                LEFT JOIN $users as u ON c.community_created_by = u.user_id 
                                LEFT JOIN $community_member m ON c.community_id = m.cmember_community_id
                                LEFT JOIN $businesses b ON b.business_id=c.community_business_id WHERE m.cmember_id = '$userId'  AND m.cmember_status = 'A' AND c.community_status != 'D' AND m.cmember_type='A'  GROUP BY c.community_id
";
    $objResultRow                  = $db->fetchAll($db->execute($query));
    return $objResultRow;
    }
    
        public function chanegeMemeberCommunityActiveStatus($objMemVo) {


        $objResult = new Messages();
        $objResult->status = SUCCESS;


        if ($objMemVo->cmember_id == '' || $objMemVo->cmember_community_id == '') {
            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // Email Alreday Exists
        }



        // Update Community data to  Community Member table 

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

            $db = new Db();

            $tableName = Utils::setTablePrefix('community_member');
            $where = "cmember_id = " . $db->escapeString($objMemVo->cmember_id) . " AND cmember_community_id = " . $db->escapeString($objMemVo->cmember_community_id) . " ";
            $customerId = $db->update($tableName, array('cmember_active_status' => $db->escapeString($objMemVo->cmember_active_status),
                    ), $where, $doAudit = false);
            $objUserVo->cmember_id = $objMemVo->cmember_id;
            $objResult->data = $objMemVo;
        }

        Logger::info($objResult);

        return $objResult;
    }
    
    public static function getCommunityActivestatus($communityId) {
         $userId                         = Utils::getAuth('user_id');
         if($userId){
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($communityId != '') {
            $db = new Db();
            $tableName = 'communities';
            $selectCase = '  community_id =' . $db->escapeString($communityId) . ' ';

            $community = Utils::setTablePrefix('communities');

            $users = Utils::setTablePrefix('users');

            $files = Utils::setTablePrefix('files');
            $category = Utils::setTablePrefix('categories');
            
            $community_member = Utils::setTablePrefix('community_member');
            $business = Utils::setTablePrefix('businesses');

             $query = "SELECT  c.*, u.*, f.*,ifnull(b.business_name,'Personal')AS business_name,b.business_alias, m.cmember_id,m.cmember_active_status,ct.category_name FROM $community c "
                     . "LEFT JOIN $files f ON c.community_image_id = f.file_id "
                     . "LEFT JOIN $users u ON c.community_created_by = u.user_id "
                     . "LEFT JOIN $business b ON b.business_id=c.community_business_id "
                     . "LEFT JOIN $community_member m ON m.cmember_community_id = c.community_id LEFT JOIN $category AS ct ON c.community_category_id = ct.category_id"
                     . " WHERE c.community_id = '" . $db->escapeString($communityId) . "' AND m.cmember_id = $userId ";

//echo $query
            Logger::info($query);

            $objResultRow = $db->fetchSingleRow($query);
            // If community exists then assign community data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign community record  to object
            else {
                $objResult->status = "ERROR";
                $objResult->message = COMMUNITY_ID_NOT_EXIST; // User not exists
            }
        }

        Logger::info($objResult);
        return $objResult;
         }
    }

    public static function getAnnouncementDetail($announcement_id){
        if($announcement_id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('community_announcements');
//        $tableName1                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT c.* FROM ".$tableName." AS c  WHERE c.community_announcement_alias='".$announcement_id."'";
        $objResultRow = $db->fetchSingleRow($query);
        return $objResultRow;
        }
    }
    
    public static function getAnnouncementCountByUser(){
        $db                             = new Db();
        $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('community_member');
        $query                          = "SELECT sum(cmember_announcement_count) AS cmember_announcement_count FROM ".$tableName." WHERE cmember_id= '".$userId."'";
        $objResultRow                   = $db->fetchAll($db->execute($query));
        return $objResultRow;
    }
    
    public static function getAnnouncementDetailById($announcement_id){
        if($announcement_id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $tableName1                     = Utils::setTablePrefix('users');
        $tableName2                     = Utils::setTablePrefix('files');
        $query                          = "SELECT c.*,U.user_firstname,U.user_lastname,U.user_alias,F.file_path FROM ".$tableName." AS c LEFT JOIN $tableName1 AS U "
                                        . "ON U.user_id = c.community_announcement_user_id LEFT JOIN $tableName2 AS F"
                                        . " ON F.file_id = U.user_image_id WHERE c.community_announcement_id='".$announcement_id."'";
        $objResultRow = $db->fetchSingleRow($query);
        return $objResultRow;
        }
    }
    
    public static function deleteGroupFeeds($announcement_id) {
        $db                         = new Db();
        $rescomm                    = $db->updateFields("community_announcements", array('community_announcement_status'=>'D'),"community_announcement_id=".$announcement_id);
        echo  $rescomm;
    }
    public static function deleteProfile($profile_id) {
        $db                         = new Db();
        $rescomm                    = $db->updateFields("users", array('user_image_name'=>'','user_image_id'=>''),"user_id=".$profile_id);
        echo  $rescomm;
    }
    
    public static function deleteNewsFeeds($announcement_id) {
        $db                         = new Db();
        $tableName = Utils::setTablePrefix('news_feed');
            $where = "news_feed_id = " . $db->escapeString($announcement_id) ." ";
            $customerId = $db->delete($tableName, $where, $doAudit = false);
            echo $customerId;
    }
    
     public static function getAllCommunitiesForUser($pagenum = 1, $itemperpage = 5, $search = '') {
        $db                 = new Db();
        $userId             = Utils::getAuth('user_id');
        $files              = Utils::setTablePrefix('files');
        $users              = Utils::setTablePrefix('users');
        $members            = Utils::setTablePrefix('community_member');
        $userWhere          = "(m.cmember_id = '" . $userId . "'   AND c.community_status != 'D') OR(c.community_status = 'A' AND community_type = 'PUBLIC' ) ";
        $objLeadData        = new stdClass();
        $objLeadData->table = 'communities AS c';
        $objLeadData->key   = 'c.community_id';
        $objLeadData->fields = 'c.*,f.*,u.*,count(m.cmember_list_id) As memberCount ';
        $objLeadData->join  = "LEFT JOIN $files AS f ON c.community_image_id= f.file_id LEFT JOIN $users as u ON c.community_created_by = u.user_id LEFT JOIN $members m ON c.community_id = m.cmember_community_id AND m.cmember_status = 'A'";
        $objLeadData->where = "$userWhere ";
        if ($search != '') {
            $objLeadData->where .= " AND (community_name LIKE  '%$search%')";
        }
        $objLeadData->groupbyfield = 'c.community_id';
        $objLeadData->orderby      = 'DESC';
        $objLeadData->orderfield   = 'community_created_on';
        $objLeadData->itemperpage  = $itemperpage;
        $objLeadData->page         = $pagenum;  // by default its 1
        $objLeadData->debug        = true;
        $leads                     = $db->getData($objLeadData);
        return $leads;
    }
    
     public static function getMyLatestDiscussionImage($community_id){
        //if($id){
        $db                             = new Db();
        //$userId                         = $_POST['uid'];
        $tableName                      = Utils::setTablePrefix('community_announcements');
        $query                          = "SELECT c.* FROM ".$tableName." AS c  WHERE c.community_id='".$community_id."' AND c.community_announcement_image_path !='' AND c.community_announcement_status = 'A' ORDER BY c.community_announcement_id DESC LIMIT 0,3";
        $objResultRow = $db->selectQuery($query);
        return $objResultRow;
       // }
    }
            }

?>
