<?php 
/*
 * All Buisiness Entity Logics should come here.
 */
class Business{
   /*
Function to Register a  new Business
*/
   public static  function createBusiness($objBusinessVo)
 { 
           // echopre1($objBusinessVo);
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
//          
//        // Insert Buisiness data to to Buisiness table 
                if($objResult->status==SUCCESS) {
                 $db                             =   new Db();

                 $tableName                      =   Utils::setTablePrefix('businesses');
                 
                 $excludeId                      =    '';
                 
                 $BusinessesAliasName                  =   Utils::generateAlias($tableName,$objBusinessVo->business_name, $idColumn="business_id",$id = $excludeId, $aliasColumn="business_alias");


                 $data = Utils::objectToArray($objBusinessVo);
                 
                 $data['business_alias'] = $BusinessesAliasName;
                 
                 $query = "SELECT count(business_name) from $tableName WHERE business_name ='".Utils::escapeString($data['business_name'])."' ";
 		 
 
 		Logger::info($query);
 		 
 		$objResultRow                   =  $db->getDataCount('businesses','business_name',"WHERE business_name ='".Utils::escapeString($data['business_name'])."'");
                //echo "here";exit;
               // echo "dfgd".$objResultRow;exit;
 		// If buisiness exists then assign buisiness data to result object
 		if($objResultRow){
                        $objResult->status          =   "ERROR";
                        $objResult->message         =   "Page Name Already Exist";
                }
 		else{
              
                 $businessId                     =   $db->insert($tableName, $data);
                 $objBusinessVo->business_id              =   $businessId;
                 $objResult->data                 =   $objBusinessVo;
                }
          }
          Logger::info($objResult);
          return $objResult;
                
 }   
 
 
 
  /*
Function to edit Business profile information
   * Parameter -  Business Data
*/
  public  function editBusiness($businessId='',$objBusinessVo)
 {
      
       $db = new Db();
       $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
          //Check Entered Buisiness Email Exists OR NOT then stop buisiness sign up if email exists
          
                    if($businessId == '') {
                        $objResult->status          =   "ERROR";
                        $objResult->message         =   GROUP_ID_NOT_EXIST; // Email Alreday Exists
                    }
                $query = "SELECT count(business_name) from $tableName WHERE business_name ='".Utils::escapeString($data['business_name'])."' ";
 		 
 
 		Logger::info($query);
 		 
 		$objResultRow                   =  $db->getDataCount('businesses','business_name',"WHERE business_name ='".Utils::escapeString($data['business_name'])."'");
                //echo "here";exit;
               // echo "dfgd".$objResultRow;exit;
 		// If buisiness exists then assign buisiness data to result object
 		if($objResultRow){
                      //  $objResult->status          =   "ERROR";
                        $objResult->message         =   "Page Name Already Exist";
                }

        
                    
        // Update Group data to  Buisiness table 
                 
                if($objResult->status==SUCCESS) {

                 $db                             =   new Db();
                 
                 $data                           =   Utils::objectToArray($objBusinessVo); 
                 $tableName                      =   Utils::setTablePrefix('businesses');
                 $where                          =   "business_id = ".Utils::escapeString($businessId)." ";
                 $customerId                     =   $db->update($tableName,$data,$where,$doAudit=false);
                 $objBusinessVo->business_id         =   $businessId;
                 $objResult->data                 =   $objBusinessVo;

          }

          Logger::info($objResult);

          return $objResult;
     
                
 }  
 
  

  /*
Function to check Customer Exists or not if exists re-direct to login 
   * Parameters  : Buisiness Id 
*/
 public static function changeBusinessStatus($businessId,$objBusinessVo='')
 {         
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
         //  Check Entered Buisiness Id  exists in the system
         if($businessId!='') {  
             
                                 $objResult->status           =   "ERROR";
                                 $objResult->message          =   GROUP_ID_NOT_EXIST; // Buisiness Id not  Exists
                         
         }         
        // Update Buisiness status to deleted  if buisiness  already exists
                if($objResult->status==SUCCESS) {

                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('businesses');
                 $selectCase                     =   '';
              
                 $where                          =  "business_id='".Utils::escapeString($businessId)."' ";    
                 $resultRows                     =  $db->update($tableName, array( 'business_status'     =>  Utils::escapeString($objBusinessVo->business_status),
                                                                                  ),$where,$doAudit=false);
                 // Update  Buisiness Account with deleted status  and Set Corresponding Message
                 if($resultRows>0)
                 { 
                      $objResult->message        =   USER_DELETED_SUCCESS; // Buisiness Deleted Successfully
                 }
                 
          }

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

 }
 
 public  function listBusiness($objTableVo)
 {    
            if($objTableVo->coulmns=='')
            {
                $objTableVo->coulmns  = '*';
            }
            
             $objTableVo->tablename          =   'businesses';
             $objResult                      =   new Messages();
             $objResult->status              =   SUCCESS;
             $db                             =   new Db();
             $objResultRows                  =   $db->getPagingData($objTableVo->coulmns,$objTableVo->tablename,$objTableVo->join,$objTableVo->criteria,$objTableVo->group_by,$objTableVo->sort_order,$objTableVo->sort_field,$objTableVo->limit);
            //Check Buisiness Details exist 
                  if($objResultRows)
              // Assign Buisiness details to object
                      $objResult->data             =    $objResultRows;          
                 else {
                        $objResult->status         =   "ERROR";
                        $objResult->message        =   USER_NOT_EXIST; // Store details not exists 
                     }
       
            Logger::info($objResult);
          
            return $objResult;
 } 
 /*
Function to get Group details
   * Parameters  : Group id
*/
 public static function getBusiness($alias='')
 {         // echo "fkdlg";exit;
                $objResult                        =   new Messages();
                $objResult->status                =   SUCCESS;
         //Select Buisiness Record If Buisiness id is not null
                if($alias!='') {
                 $db                                =   new Db();
                 $business                          =   Utils::setTablePrefix('businesses');
                 $files                             =   Utils::setTablePrefix('files');
                 $users                             =   Utils::setTablePrefix('users');
                 //$industry                          =   Utils::setTablePrefix('industry');
                 $country                           =   Utils::setTablePrefix('country');
                 $state                             =   Utils::setTablePrefix('state');
                 $category                          =   Utils::setTablePrefix('categories');
                 
                 $query =  "SELECT B.*,U.*,F.*,$country.tc_name AS Country,$state.ts_name AS State,C.category_name  from $business B LEFT JOIN $category AS C ON B.business_category_id=C.category_id   LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           LEFT JOIN $users U ON  B.business_created_by = U.user_id
                          
                           LEFT JOIN $country ON $country.tc_code = B.business_country  
                           LEFT JOIN $state ON $state.ts_code = B.business_state 
                            AND  $state.tc_id=$country.tc_id   
                           WHERE business_alias = '".mysql_real_escape_string(Utils::escapeString($alias))."'";
                 
                
                 Logger::info($query);
               // echo $query;exit;
                 $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         =   BUSINESS_ID_NOT_EXIST; // Buisiness not exists
                  }
          }

            Logger::info($objResult);
            return $objResult;
 }
  public static function getBusinessSearch($searchString='')
 {         
                $objResult                        =   new Messages();
                $objResult->status                =   SUCCESS;
         //Select Buisiness Record If Buisiness id is not null
                if($searchString!='') {
                 $db                             =   new Db();
                 $business                      =   Utils::setTablePrefix('businesses');
                 $files                      =   Utils::setTablePrefix('files');
                 $users                     =   Utils::setTablePrefix('users');
                 
                 
                 $query = "SELECT B.business_name as label,B.business_alias as value,F.file_path as image,'business' AS type from $business B LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           LEFT JOIN $users U ON  B.business_created_by = U.user_id
                           
                           WHERE business_name like '%".$searchString."%' AND business_status = 'A' limit 3";
                 
               
                 Logger::info($query);
                 
               $objResultRow = $db->fetchAll($db->execute($query));
         // If buisiness exists then assign buisiness data to result object
                
          }

            Logger::info($objResultRow);
            return $objResultRow;
 }
 
 
 public static function getBusinessSearchAll($searchString='')
 {         
                $objResult                        =   new Messages();
                $objResult->status                =   SUCCESS;
         //Select Buisiness Record If Buisiness id is not null
                if($searchString!='') {
                 $db                             =   new Db();
                 $business                      =   Utils::setTablePrefix('businesses');
                 $files                      =   Utils::setTablePrefix('files');
                 $users                     =   Utils::setTablePrefix('users');
                 
                 
                 $query = "SELECT B.business_name as label,B.business_alias as value,B.business_id AS id,F.file_path as image,'business' AS type from $business B LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           LEFT JOIN $users U ON  B.business_created_by = U.user_id
                           
                           WHERE business_name like '%".$searchString."%' AND business_status = 'A'";
                 
               
                 Logger::info($query);
                 
               $objResultRow = $db->fetchAll($db->execute($query));
         // If buisiness exists then assign buisiness data to result object
                
          }

            Logger::info($objResultRow);
            return $objResultRow;
 }
 
  public static function getDesignationSearchAll($searchString='')
 {         
                $objResult                        =   new Messages();
                $objResult->status                =   SUCCESS;
         //Select Buisiness Record If Buisiness id is not null
                if($searchString!='') {
                 $db                             =   new Db();
                 $designation                      =   Utils::setTablePrefix('designation');
                 
                 
                 $query = "SELECT designation_title as label FROM $designation 
                           WHERE designation_title like '%".$searchString."%' AND designation_status = 'A'";
                 
           
                 Logger::info($query);
                 
               $objResultRow = $db->fetchAll($db->execute($query));
         // If buisiness exists then assign buisiness data to result object
                
          }

            Logger::info($objResultRow);
            return $objResultRow;
 }
 
 public static function getBusinessId($alias='')
 {
    // $pdo = new PdoClass();
     //echo "kjfgdkg";exit
 	$objResult                        =   new Messages();
 	$objResult->status                =   SUCCESS;
 	//Select Buisiness Record If Buisiness id is not null
 	if($alias!='') {
 		$db                             =   new Db();
 		$business                      =   Utils::setTablePrefix('businesses'); 		
 		 
 		$query = "SELECT business_id from $business B WHERE business_alias = '".mysql_real_escape_string(Utils::escapeString($alias))."'";
 		 
             //   echo $query;exit;
 		Logger::info($query);
 		// echo "kfgjk";
 		$objResultRow                   =  $db->fetchSingleRow($query);
              //  $objResultRow = PdoClass::pdoQuery($query)->result();
 		// 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 Group details
   * Parameters  : Group id
*/
 public static function getBusinessById($id)
 {         
                $objResult                        =   new Messages();
                $objResult->status                =   SUCCESS;
         //Select Buisiness Record If Buisiness id is not null
                
                 if(!$id)
                 {
                     
                     $objResult->status                =   ERROR;
                     $objResult->message               =   GROUP_ID_NOT_EXIST;
                 }
                
                
                
                if($objResult->status == SUCCESS) {
                 $db                             =   new Db();
                 $business                      =   Utils::setTablePrefix('businesses');
                 $files                      =   Utils::setTablePrefix('files');
                 $users                     =   Utils::setTablePrefix('users');
                 
                 
                 $query = "SELECT B.*,U.*,F.* from $business B LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           LEFT JOIN $users U ON  B.business_created_by = U.user_id
                           WHERE business_id ='".Utils::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;
 }
// public static function updateBusinessRegisterTime($businessId)
// {
// 	$db                             = new Db();
// 	$table                          = 'businesses';
// 	$dataArray                      = array();
// 		
// 	$data = $db->selectRecord($table, 'business_name,business_image_id', 'business_id = '.$businessId);
// 	if($data->business_image_id >0){
// 		$file = $db->selectRow('files', 'file_path', 'file_id = '.$data->business_image_id);
//           if($width >= 256 || $height >= 242){
//                
//            Utils::allResize($image, 'medium', 256, 242);
//            Utils::allResize($image, 'small', 190, 134);
//            Utils::allResize($image, '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);
// 	}
// 	$businessAliasName                  =   Utils::generateAlias(MYSQL_TABLE_PREFIX.$table,$data->business_name, $idColumn="business_id",$id = $excludeId, $aliasColumn="business_alias");
// 	$dataArray['business_alias']         = $businessAliasName;
// 	$dataArray['business_status']         = 'A';
// 	$dataArray['business_created_on']         = date('Y-m-d H:i:s');
// 
// 	$db->update(MYSQL_TABLE_PREFIX.$table, $dataArray,'business_id="'.mysql_real_escape_string($businessId).'"');
// 
// 
// }
 
// public static function updateBusinessFile($userId)
// {
// 	$db                             = new Db();
// 	$table                          = 'businesses';
// 
// 	$data = $db->selectRow($table, 'business_image_id', 'business_id = '.$userId);
// 	//echopre($data);
// 	//exit;
// 	$file = $db->selectRow('files', 'file_path', 'file_id = '.$data);
//        if($width >= 256 || $height >= 242){
//                
//            Utils::allResize($image, 'medium', 256, 242);
//            Utils::allResize($image, 'small', 190, 134);
//            Utils::allResize($image, '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 updatebusinessCount($id = '')
 {
        $db                             = new Db();
 	$business                      =   Utils::setTablePrefix('businesses'); 
        $users                           =  Utils::setTablePrefix('users');
 	$dataArray                      = array();
 	if($id == ''){
        $userId = Utils::getAuth('user_id');
 	}
 	else{
 		$userId = $id;
 	}
        $query = "SELECT count(*) AS c from $business WHERE business_created_by ='".Utils::escapeString($userId)."' AND business_status !='D' ";
        
        
        Logger::info($query);
        $objResultRow                   =  $db->selectQuery($query);
        
       // echopre($objResultRow);
        
         $count = ($objResultRow[0]->c)?$objResultRow[0]->c:0;
         
         $data = array();   
         $data['user_business_count']   = $count;
         $where                          =   "user_id = ".Utils::escapeString($userId)." ";    
         $customerId                     =   $db->update($users, $data,$where,$doAudit=false);
        
        
 }


 
 
 
 public static function getState($business_id='')
 {
 	$tableName                      =  'businesses';
 
 	$db                             =   new Db();
 
 	if($business_id > 0){
 		$andCase                        = "  business_id =".Utils::escapeString($business_id)."  ";
 
 	$result = $db->selectRow($tableName,"business_state",$andCase);
 	//print_r($result);
 	Logger::info($result);
        }
 	return $result;
 }
 
  public static function getAllBusiness($orderfield='business_name',$orderby='ASC',$pagenum=1,$itemperpage=10,$search='',$searchFieldArray,$userId='',$groupby,$from = '') {
  
        $db = new Db();
        
         $files                      =   Utils::setTablePrefix('files');
         
         $users                      =   Utils::setTablePrefix('users');
         $categories                      =   Utils::setTablePrefix('categories');
        
         if($userId >0 )
         {
             if($from != ''){
               $userWhere = " b.business_status != 'D' AND b.business_created_by != '".$userId."' ";  
             }
             else{
               $userWhere = " b.business_status != 'D' AND b.business_created_by = '".$userId."' ";
             }
         }else{
             $userWhere = " b.business_status != 'D'";
         }
         if($groupby){
           $userWhere .= ' AND b.business_category_id = '.$groupby;
        }
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'businesses AS b';
        $objLeadData->key           = 'b.business_id';
        $objLeadData->fields	    = 'b.*,f.*,u.user_firstname,u.user_lastname,c.category_name';
        $objLeadData->join	    = "LEFT JOIN $categories AS c ON c.category_id = b.business_category_id LEFT JOIN $files AS f ON b.business_image_id= f.file_id LEFT JOIN $users as u ON b.business_created_by = u.user_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 = '';  
        $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);exit;
        //return $leads->records;
        return $leads;
    }
    
    public static function getAllBusinessWithCount($orderfield, $orderby,$page,$itemperpage,$search)
 {
       // echo $categoryid;exit;
 	$db                             = new Db();
 	$table                          = Utils::setTablePrefix('businesses');
 	$communities                    = Utils::setTablePrefix('communities');
        $files                    = Utils::setTablePrefix('files');
        $userId                         = Utils::getAuth('user_id');
        if($userId >0 )
         {
             $userWhere = "b.business_created_by = '".$userId."'  AND b.business_status != 'D' ";
         }else{
             $userWhere = "b.business_status = 'A'  ";
         }
         	if($itemperpage) 	$itemPerPage 	= $itemperpage;
 		else 						$itemPerPage 	= PAGE_LIST_COUNT;
// 		
 		if($page) 			$currentPage 	= $page;
 		else 						$currentPage 	= '1';
// 		$totPages 					= ceil($totRecords/$itemPerPage);
// 		$objRes->totpages 			= $totPages;
// 		$objRes->currentpage 		= $currentPage;

 		// get the limit of the query
                if($page){
 		$limitStart = ($currentPage * $itemPerPage) - $itemPerPage;
 		$limitEnd 	= $itemPerPage;
 		$limitVal 	= ' LIMIT '.$limitStart.','.$limitEnd;
                }
                else{
                    $limitVal ='';
                }

 	$query = "SELECT f.file_path,b.*,count(c.community_id) AS cnt FROM $table b "
                . "LEFT JOIN $communities c on  c.community_business_id  = b.business_id AND c.community_status = 'A' "
                . " LEFT JOIN $files f ON f.file_id = b.business_image_id "
                . "WHERE $userWhere GROUP BY b.business_id ORDER BY b.business_name ".$orderby;
        //echo $query;
//  	$data1 = $db->selectResult('categories', '*', "category_status = 'A'");
    $data1 = $db->selectQuery($query); 
//     echopre($data1);
 	 $dataArray = new stdClass();
 	// $dataArray->data = $data1;
 	 
 	 $dataArray->totalrecords = count($data1);
  	 //echopre($dataArray);
 	//  	exit;
    $query1 = "SELECT f.file_path,b.*,count(c.community_id) AS cnt FROM $table b "
            . "LEFT JOIN $communities c on  c.community_business_id  = b.business_id AND c.community_status = 'A' "
            . "LEFT JOIN $files f ON f.file_id = b.business_image_id "
            . "WHERE $userWhere GROUP BY b.business_id ORDER BY b.business_name ".$orderby.$limitVal;
        $data = $db->selectQuery($query1); 
      // echo $query1;
        $dataArray->data = $data;
 	return $dataArray;
 
 }

    public static function getAllTaggedBusinessWithCount($orderfield, $orderby, $page, $itemperpage, $search)
    {
        $db = new Db();
        $taggedbusiness = Utils::setTablePrefix('tagged_business');
        $table = Utils::setTablePrefix('businesses');
        $communities = Utils::setTablePrefix('communities');
        $files = Utils::setTablePrefix('files');
        $userId = Utils::getAuth('user_id');
        
        if ($userId > 0) {
            $userWhere = " b.user_id = '" . $userId . "'  AND bs.business_status != 'D' ";
        } else {
            $userWhere = " bs.business_status != 'D'  ";
        }
        
        if ($itemperpage){
            $itemPerPage = $itemperpage;
        } else {
            $itemPerPage = PAGE_LIST_COUNT;
        }                        
        
        if ($page) {
            $currentPage = $page;
        } else {
            $currentPage = '1';
        }
        
        if ($page) {
            $limitStart = ($currentPage * $itemPerPage) - $itemPerPage;
            $limitEnd = $itemPerPage;
            $limitVal = ' LIMIT ' . $limitStart . ',' . $limitEnd;
        } else {
            $limitVal = '';
        }
        if($search!=''){
          $like =   " AND bs.business_name LIKE '%".$search."%' ";
        }
        else{
            $like = '';
        }

        $query = "SELECT f.file_path, b.*,bs.*,count(c.community_id) AS cnt FROM  $taggedbusiness  b 
            LEFT JOIN $table bs ON bs.business_id = b.business_id 
            LEFT JOIN $communities c on  c.community_business_id  = b.business_id AND c.community_status = 'A' 
                LEFT JOIN $files f on f.file_id = bs.business_image_id 
                WHERE $userWhere $like GROUP BY b.business_id ORDER BY bs.business_name " . $orderby;
        $data1 = $db->selectQuery($query);
        
        $dataArray = new stdClass();
        $dataArray->totalrecords = count($data1);
        
        $query1 = "SELECT f.file_path,b.*,bs.*,count(c.community_id) AS cnt 
        FROM $table  bs 
        LEFT JOIN $taggedbusiness  b ON bs.business_id = b.business_id    
        LEFT JOIN $communities c on  c.community_business_id  = b.business_id AND c.community_status = 'A' 
            LEFT JOIN $files f on f.file_id = bs.business_image_id 
            WHERE $userWhere $like GROUP BY b.business_id ORDER BY bs.business_name " . $orderby . $limitVal;
        
        $data = $db->selectQuery($query1);
        $dataArray->data = $data;
        
        return $dataArray;
    }
 
 
    public  static function updateStatusDelete($communityId='')
    {
    
    	$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         =   GROUP_ID_NOT_EXIST; // Email Alreday Exists
    	}
    
    
    
    	// Update Community data to  Community table
    		
    	if($objResult->status==SUCCESS) {
    
    		$db                             =   new Db();
    
    		$tableName                      =   Utils::setTablePrefix('businesses');
    		$where                          =   "business_id = ".Utils::escapeString($communityId)." ";
    
    		$data = array('business_status' => 'D');
    
    		$customerId                     =   $db->update($tableName, $data,$where,$doAudit=false);
    		//$objUserVo->community_id         =   $communityId;
    		$objResult->data                 =   $data;
    
    	}
    
    	Logger::info($objResult);
    
    	return $objResult;
    		
    }
    
    
     
    public static function addTagg($objTag)
    {
        
        $objResult                      =   new Messages();
    	$objResult->status              =   SUCCESS;
        $data                           =   array();
       if($objTag->business_id == '') {
    		$objResult->status          =   "ERROR";
    		$objResult->message         =   INVALID_PAR; // Email Alreday Exists
    	}
        
         $tableName                      =   Utils::setTablePrefix('tagged_business');
         
          
        if($objResult->status==SUCCESS) {
    
    		$db                             =   new Db();
                $userId                         = Utils::getAuth('user_id');
                
                if($objTag->tagg_id){
                
    		
    		$where                          =   "tagg_id = ".Utils::escapeString($objTag->tagg_id)." ";
    
    		$data = Utils::objectToArray($objTag);
    
    		$tagg_id                     =   $db->update($tableName, $data,$where,$doAudit=false);
                
                $tagg_id = $objTag->tagg_id;
                
                $objResult->message         =   EDIT_TAG_SUCCESS;
                }else{
                    
                    $data = Utils::objectToArray($objTag);
                     $objResultRow             =  $db->getDataCount('tagged_business','business_id',"WHERE business_id ='".$objTag->business_id."' AND user_id = ".$userId);
                    // echo "ehfjhfg". $objResultRow;exit;
//                    if($objResultRow){
//                        $objResult->status          =   "ERROR";
//                        $objResult->message         =   "Role exist";
//                  }
                  if(!$objResultRow){
                      $tagg_id                     =   $db->insert($tableName, $data);
                    $objResult->message         =   TAG_SUCCESS;
                  }
                    
                }
    		//$objUserVo->community_id         =   $communityId;
    		$objResult->tagg_id                 =   $tagg_id;
                
    $objResult->data                =   $objTag;
    	}
    
    	Logger::info($objResult);
    
    	return $objResult;
        
        
    }
    
    
    public static function removeTag($tagg_id)
    {
         $db                             =   new Db();
          $tableName                      =   Utils::setTablePrefix('tagged_business');
         $id =  $db->deleteRecord('tagged_business','tagg_id='.$tagg_id.'');
         return $id;
    }
    
    public static function addAffiliateToBusiness($user_id,$business_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('business_affiliates');
                 $id                             =  $db->deleteRecord('business_affiliates','business_id='.$business_id.' AND user_id='.$user_id);
                 $data                           = array('business_id'=>$business_id,
                                                          'user_id'=>$user_id,
                                                          'business_affiliate_created_date'=>date('Y-m-d')
                                                            );
                 $businessId                     =   $db->insert($tableName, $data);
                 self::updateAffilaitionstatusForTaggedBiz($business_id,$user_id,'Y');
                 $objBuisinessVo->affiliate_id    =   $businessId;
                 $objResult->data                =   $objBusinessVo;
          }
          Logger::info($objResult);
          return $objResult;
    }
    
     public static function removeAffiliate($user_id,$business_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('business_affiliates');
                 $data                           = array('business_affiliate_status'=>'D'
                                                            );
                 $where                          = 'business_id='.$business_id.' AND user_id='.$user_id;
                 $businessId                     =   $db->update($tableName, $data,$where,$doAudit=false);
                 self::updateAffilaitionstatusForTaggedBiz($business_id,$user_id,'N');
                 $objBuisinessVo->affiliate_id    =   $businessId;
                 $objResult->data                =   $objBusinessVo;
          }
          Logger::info($objResult);
          return $objResult;
    }
    
     public static function getAllAffiliatesIdForBusiness($business_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             = new Db();
                 $tableName                      = Utils::setTablePrefix('business_affiliates');
                 $query                          = sprintf("SELECT user_id FROM $tableName WHERE business_affiliate_status='A' AND business_id= %s , ".  mysql_real_escape_string($business_id));
                 $objResult                      = $db->fetchAll(mysql_query($query));
                 foreach($objResult AS $users){
                     $userlist[]    =   $users->user_id;
                 }
          }
         // Logger::info($objResult);
          return $userlist;
    }
    
    public static function getAllAffiliatesForBusiness($businessId,$orderfield='business_affiliate_id',$orderby='Desc',$pagenum=1,$itemperpage=10,$search='',$searchFieldArray) {
      
        $db                               = new Db();
        $business                         =   Utils::setTablePrefix('businesses');
        $affiliates                       =   Utils::setTablePrefix('business_affiliates');
        $files                            =   Utils::setTablePrefix('files');
        $users                            =   Utils::setTablePrefix('users');
 
        
        
             $where = " A.business_affiliate_status='A' AND A.business_id=$businessId";
         
         
         
         
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'business_affiliates AS A';
        $objLeadData->key           = 'A.business_affiliate_id';
        $objLeadData->fields	    = 'A.*,B.*,F.*,U.*';
        $objLeadData->join	    = "INNER JOIN $business B ON A.business_id = B.business_id 
                                            INNER JOIN  $users U ON U.user_id  = A.user_id    
                                            LEFT JOIN $files F ON U.user_image_id = F.file_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++;
            }
        }
        $objLeadData->groupbyfield  = '';
        $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 updateAffilaitionstatusForTaggedBiz($business_id,$user_id,$status){
        $where          = 'business_id=' . $business_id . ' AND user_id=' . $user_id;
        $db             = new Db();
        $tableName      = Utils::setTablePrefix('tagged_business');
        $data           = array('affiliation_status' => $status);
        $businessId = $db->update($tableName, $data,$where,$doAudit=false);
    }
    
    public static function requestAffiliateToBusiness($business_id,$user_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('business_affiliates');
                 $data                           = array('business_id'=>$business_id,
                                                          'user_id'=>$user_id,
                                                          'business_affiliate_created_date'=>date('Y-m-d'),
                                                           'business_affiliate_status'=>'R'
                                                            );
                 $businessId                     =   $db->insert($tableName, $data);
                 self::updateAffilaitionstatusForTaggedBiz($business_id,$user_id,'R');
                 $objBuisinessVo->affiliate_id    =   $businessId;
                 $objResult->data                =   $objBusinessVo;
          }
          Logger::info($objResult);
          return $objResult;
    }
    
    public static function acceptAffiliateToBusiness($business_id,$user_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('business_affiliates');
                 $data                           = array('business_affiliate_status'=>'A'
                                                            );
                 $where                          = 'business_id='.$business_id.' AND user_id='.$user_id;
                 $businessId                     =   $db->update($tableName, $data,$where,$doAudit=false);
                 self::updateAffilaitionstatusForTaggedBiz($business_id,$user_id,'Y');
                 $objBuisinessVo->affiliate_id    =   $businessId;
                 $objResult->data                =   $objBusinessVo;
          }
          Logger::info($objResult);
          return $objResult;  
    }
    
    public static function declineAffiliateToBusiness($business_id,$user_id){
            $objResult                      =   new Messages();
            $objResult->status              =   SUCCESS;
            if($objResult->status==SUCCESS) {
                 $db                             =   new Db();
                 $tableName                      =   Utils::setTablePrefix('business_affiliates');
                 $data                           = array('business_affiliate_status'=>'E'
                                                            );
                 $where                          = 'business_id='.$business_id.' AND user_id='.$user_id;
                 $businessId                     =   $db->update($tableName, $data,$where,$doAudit=false);
                 self::updateAffilaitionstatusForTaggedBiz($business_id,$user_id,'N');
                 $objBuisinessVo->affiliate_id    =   $businessId;
                 $objResult->data                =   $objBusinessVo;
          }
          Logger::info($objResult);
          return $objResult;  
    }
    
    public static function getBusinessAffilationStatus($user_id,$business_id){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('business_affiliates');
        $query                          =   "SELECT business_affiliate_id FROM ".$tableName. " WHERE business_id=".$business_id." AND user_id=".$user_id;
        $objResultRow                   = $db->fetchSingleRow($query);
        if($objResultRow->business_affiliate_id >0){
            return Y;
        }
        else{
            return N;
        }
        
    }
       
    public static function getBusinessOwnerCCStatus($business_id){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('businesses');
        $query                          =   "SELECT business_created_by FROM ".$tableName. " WHERE business_id=".$business_id;
        $objResultRow                   = $db->fetchSingleRow($query);
        return User::getMyCCStatus($objResultRow->business_created_by);
    }
    
    public static function getAllBizcomByBusiness($business_id,$pagenum = 1,$itemperpage=10){
       // echo "dfgj";exit;
        $db = new Db();
        $business                         =   Utils::setTablePrefix('businesses');
        $members                          =   Utils::setTablePrefix('community_member');
        $tagged                           =   Utils::setTablePrefix('tagged_business');
        $files                            =   Utils::setTablePrefix('files');
        $users                            =   Utils::setTablePrefix('users');
 
        $where                           = "community_status ='A' 
                                            AND C.community_business_id = '".Utils::escapeString($business_id)."'";
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'communities AS C';
        $objLeadData->key           = 'C.community_id';
        $objLeadData->fields	    = "C.*,F.*,(SELECT count(cmember_list_id) 
                                        FROM $members M  
                                        WHERE M.cmember_community_id=C.community_id AND cmember_status='A') AS member_count";
        $objLeadData->join	    = "LEFT JOIN $files F ON C.community_image_id = F.file_id ";
        $objLeadData->where	    = $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  = '';
        $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 addTaggs($objTag)
    {
        //print_r($objTag);exit;
       // echo "dfgdg".$objTag->business_id;exit;
        $objResult                      =   new Messages();
    	$objResult->status              =   SUCCESS;
        $data                           =   array();
       if($objTag['business_id'] == '' ||  $objTag['role']=='') {
    		$objResult->status          =   "ERROR";
    		$objResult->message         =   INVALID_PAR; // Email Alreday Exists
    	}
        
         $tableName                      =   Utils::setTablePrefix('tagged_business');
         
          
        if($objResult->status==SUCCESS) {
    
    		$db                             =   new Db();
                    $data = Utils::objectToArray($objTag);
                    $objResultRow             =  $db->getDataCount('tagged_business','business_id',"WHERE business_id ='".$objTag['business_id']."'");
                    if($objResultRow){
                        $objResult->status          =   "ERROR";
                        $objResult->message         =   "Role exist";
                  }
                  else{
                       $tagg_id                     =   $db->insert($tableName, $data);
                    $objResult->message         =   TAG_SUCCESS;
                  }
                   // echo $data;exit;
                   
                }
    		//$objUserVo->community_id         =   $communityId;
    		$objResult->tagg_id                 =   $tagg_id;
    
    
    	Logger::info($objResult);
    
    	return $objResult;
        
        
    }
   
    public static function getBusinesscategory($search = ''){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('businesses');
        $categories                      = Utils::setTablePrefix('categories');
        $userId = Utils::getAuth('user_id');
        if($search!=''){
             $search_val        .= " AND c.category_name LIKE '%" . Utils::escapeString($search) . "%'";
        }
        else{
           $search_val = ''; 
        }
        $query                          = "SELECT c.category_name,c.category_id, count(b.business_alias) as cnt FROM  $tableName AS b INNER JOIN $categories AS c ON c.category_id=b.business_category_id AND b.business_status ='A' AND b.business_created_by = '$userId' $search_val GROUP BY b.business_category_id ";
       // echo $query;
        $objResult                      = $db->fetchAll($db->execute($query));
      //  echopre($objResult);
        return $objResult;
    }
    
      public static function getBusinessCommunityAlias($community_alias){
        $db                             = new Db();
        $tableName                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT C.community_business_id FROM  $tableName AS C WHERE C.community_alias = '".$community_alias."'";
       // echo $query;
        $objResult                      = $db->fetchAll($db->execute($query));
       //echopre1($objResult[0]);
        return $objResult[0];
    }
    
     public static function getAnnouncements($pagenum = '',$organizationId,$itemperpage=''){
        $db                             = new Db();
        $userId                 = Utils::getAuth('user_id');
        if($userId){
        $tableName                      = Utils::setTablePrefix('organization_announcements');
        $tableName1                      = Utils::setTablePrefix('files');
        $tableName2                     = Utils::setTablePrefix('businesses');
        $tableName3                     = Utils::setTablePrefix('users');
        $tableName4                     = Utils::setTablePrefix('organization_announcement_comments');
        $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 =' . Utils::escapeString($userId).' AND cmember_community_id='.$organizationId;
            $ancmntcount                 = 0;
//            $db->update($tableName3, array('cmember_announcement_count' => $ancmntcount), $where, $doAudit = false);

        
        $likes                      = Utils::setTablePrefix('organization_announcement_likes');
        $query                          = "SELECT C.*,U.user_firstname,U.user_lastname,U.user_alias,DATEDIFF('$date',C.organization_announcement_date) as days,C.organization_announcement_date as news_feed_date,F.file_path,"
                                        . "(SELECT announcement_like from $likes l WHERE "
                                        . "l.user_id = ".$userId." AND l.announcement_id = C.organization_announcement_id AND l.organization_id =".$organizationId." )AS hasLiked, "
                                        . "(SELECT COUNT(organization_announcement_like_id) from $likes l WHERE "
                                        . "l.announcement_like = '1' AND l.announcement_id = C.organization_announcement_id)AS Count "
                                        . "FROM ".$tableName." AS C LEFT JOIN $tableName3 AS U ON U.user_id = C.organization_announcement_user_id LEFT JOIN ".$tableName1." AS F ON "
                                        . "F.file_id = U.user_image_id LEFT JOIN ".$tableName2." AS CM ON "
                                        . "CM.business_id = C.organization_id WHERE C.organization_id=".$organizationId." AND C.organization_announcement_status !='D' ORDER BY "
                                        . "C.organization_announcement_date DESC $limitVal";
       // echo $query;
        $objResultRow                   = $db->fetchAllArray($db->execute($query));
        $objResult->data = $objResultRow;
        return $objResult;
        }
    }
    
     public static function getAnnouncementsNewsfeed($pagenum = '',$organizationId,$itemperpage='',$userId){
        $db                             = new Db();
        $userId                 = $userId;
        if($userId){
        $tableName                      = Utils::setTablePrefix('organization_announcements');
        $tableName1                      = Utils::setTablePrefix('files');
        $tableName2                     = Utils::setTablePrefix('businesses');
        $tableName3                     = Utils::setTablePrefix('users');
        $tableName4                     = Utils::setTablePrefix('organization_announcement_comments');
        $tableName5                     = Utils::setTablePrefix('tagged_business');
        $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 =' . Utils::escapeString($userId).' AND cmember_community_id='.$organizationId;
            $ancmntcount                 = 0;
//            $db->update($tableName3, array('cmember_announcement_count' => $ancmntcount), $where, $doAudit = false);

        
        $likes                      = Utils::setTablePrefix('organization_announcement_likes');
        $query                          = "SELECT C.*,U.user_firstname,U.user_lastname,U.user_alias,DATEDIFF('$date',C.organization_announcement_date) as days,C.organization_announcement_date as news_feed_date,F.file_path,CM.business_name,business_alias,"
                                        . "(SELECT COUNT(organization_announcement_like_id) from $likes l WHERE "
                                        . "l.announcement_like = '1' AND l.announcement_id = C.organization_announcement_id)AS Count "
                                        . "FROM ".$tableName." AS C LEFT JOIN $tableName3 AS U ON U.user_id = C.organization_announcement_user_id LEFT JOIN ".$tableName1." AS F ON "
                                        . "F.file_id = U.user_image_id LEFT JOIN ".$tableName2." AS CM ON "
                                        . "CM.business_id = C.organization_id WHERE C.organization_id IN(SELECT business_id FROM $tableName5 WHERE user_id = $userId )AND C.organization_announcement_status !='D' ORDER BY "
                                        . "C.organization_announcement_date DESC $limitVal";

        $objResultRow                   = $db->fetchAllArray($db->execute($query));
        $objResult->data = $objResultRow;
        return $objResult;
        }
    }

    /**
     * Returns images related to a specific organization
     *
     * @param int $organizationId
     * @param int $pagenum
     * @return array $images
     */
    public static function getAnnouncementImages($pagenum = 1,$organizationId)
    {
        $orderfield = 'organization_announcement_id';
        $orderby = 'DESC';
        $itemsPerPage = 8;

        $db = new Db();
        $query = new stdClass();
        $query->table = 'organization_announcements AS o';
        $query->key = 'o.organization_announcement_id';
        $query->fields = 'o.*';
        $query->where = "o.organization_id='" . $organizationId . "' AND o.organization_announcement_status = 'A' AND organization_announcement_image_id != 0";
        $query->groupbyfield = '';
        $query->orderby = $orderby;
        $query->orderfield = $orderfield;
        $query->itemperpage = $itemsPerPage;
        $query->page = $pagenum;
        $query->debug = true;
        
        $ImageObj = $db->getData($query);
        return $ImageObj;
    }

    public static function getAllComments($orderfield = 'comment_id', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $entity_type = '', $entity_id = '')
    {

        $db = new Db();
        
         $files                      =   Utils::setTablePrefix('files');
        
         $users                      =   Utils::setTablePrefix('users');
        
         if($entity_type)
         {
             $userWhere = " AND c.comment_entity_type = '".$entity_type."' AND  c.comment_entity_id = '".$entity_id."' ";
         }else{
             $userWhere = '';
         }
         
         
         
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'comments AS c';
        $objLeadData->key           = 'c.comment_id';
        $objLeadData->fields	    = 'c.*,f.*,u.*';
        $objLeadData->join	    = "LEFT JOIN $users AS u ON c.comment_created_by = u.user_id LEFT JOIN $files as f ON u.user_image_id = f.file_id";
        $objLeadData->where	    = "c.comment_status = 'A' $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  = '';
        $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 addOrgNewsfeedImage($objUserImageData,$width,$height) {
        //echo "here";exit;
        //echopre($_FILES);exit;
        $db = new Db();
        $table = 'users';
        $dataArray = array();
        $msg = array();
        try {
            $fileHandler = new Filehandler();
            $emailLogoFileDetails = $fileHandler->handleUpload($_FILES['file']);
            $image_id = $emailLogoFileDetails->file_id;
            $image = $emailLogoFileDetails->file_path;
             if($width >= 800 || $height >= 480){
                
            Utils::allResize($image, 'medium', '', 480);
            Utils::allResize($image, 'small', '', 164);
            Utils::allResize($image, 'thumb', '', 50);
            }
            else{
            Utils::allResize($image, 'medium', $width, $height);
            if($width >= 178 || $height >= 164){
                Utils::allResize($image, 'small', '', 164);
                
            }
            else{
               Utils::allResize($image, 'small', $width, $height); 
            }
            if($width >= 50 || $height >= 50){
                Utils::allResize($image, 'thumb', '', 50);
                
            }
            else{
               Utils::allResize($image, 'thumb', $width, $height); 
            }
//            Utils::allResize($image, 'small', 178, 164);
//            Utils::allResize($image, 'thumb', 50, 50);
            }
            $dataArray['organization_announcement_image_path'] = $image;
            $dataArray['organization_announcement_image_id'] = $image_id;
            // $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'user_id="' . mysql_real_escape_string($objUserImageData->user_id) . '"');
            // $msg['msg']                     = PROFILE_PIC_CHANGED;
            //$msg['msgcls']                  = 'success_div';
            $msg['file'] = $image;
            $data = array();
            $tableName = Utils::setTablePrefix('organization_announcements');
            $data['organization_id']        = $objUserImageData->organization_id;
            $AliasName = Utils::generateAlias($tableName, $data['organization_announcement_content'], $idColumn = "organization_announcement_id", $id = $excludeId, $aliasColumn = "organization_announcement_alias");
            $data['organization_announcement_alias'] = $AliasName;
//            $data['news_feed_user_name'] = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
            $data['organization_announcement_date'] = date('Y-m-d H:i:s');
            $data['organization_announcement_content'] = $objUserImageData->organization_announcement_content;
            $data['organization_announcement_user_id'] = $objUserImageData->organization_announcement_user_id;
            $data['organization_announcement_image_id'] = $image_id;
            $data['organization_announcement_image_path'] = $image;
            //$data['announcement_image_status']          = 'I';
           // $data['news_feed_date'] = $objUserImageData->news_feed_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;
        }
        $msg['image_id'] = $announcement_comment_image_id;
        return $msg;
    }
    
    public static function changeOrgfeedComment($data, $feedid) {
        $db = new Db();
        $userId = Utils::getAuth('user_id');
        $tableName = Utils::setTablePrefix('organization_announcements');
        $AliasName = Utils::generateAlias($tableName, $data['organization_announcement_content'], $idColumn = "organization_announcement_id", $id = $excludeId, $aliasColumn = "organization_announcement_alias");
        $data['organization_announcement_alias'] = $AliasName;
        $data['organization_announcement_date'] = date('Y-m-d h:i:s a', time());
        if ($feedid > 0) {
            $where = "organization_announcement_id = " . Utils::escapeString($feedid);
            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
        } else {
            $data['organization_announcement_user_id'] = $userId;
            $customerId = $db->insert($tableName, $data);
        }
        return $customerId;
    }

    public static function getAnnouncementDetailById($announcement_id){
        if($announcement_id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('organization_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 c.organization_announcement_user_id = U.user_id"
                . " LEFT JOIN $tableName2 AS F ON F.file_id = U.user_image_id  WHERE c.organization_announcement_id='".$announcement_id."'";
        $objResultRow = $db->fetchSingleRow($query);
        return $objResultRow;
        }
    }
    
    public static function addCommentImage($objUserImageData,$width, $height) {
        //echo "here";exit;
        //echopre($_FILES);exit;
        $db = new Db();
        $table = 'users';
        $dataArray = array();
        $msg = array();
        try {
            $fileHandler = new Filehandler();
            $emailLogoFileDetails = $fileHandler->handleUpload($_FILES['file']);
            $image_id = $emailLogoFileDetails->file_id;
            $image = $emailLogoFileDetails->file_path;
            if($width >= 178 || $height >= 164){
                
            Utils::allResize($image, 'medium', 178, 164);
            Utils::allResize($image, 'small', 75, 75);
            Utils::allResize($image, 'thumb', 50, 50);
            }
            else{
            Utils::allResize($image, 'medium', $width, $height);
            //Utils::allResize($image, 'small', $width, $height);
            if($width >= 75 || $height >= 75){
                Utils::allResize($image, 'small', 75, 75);
                
            }
            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($image, 'medium', 178, 164);
//            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="' . mysql_real_escape_string($objUserImageData->user_id) . '"');
            // $msg['msg']                     = PROFILE_PIC_CHANGED;
            //$msg['msgcls']                  = 'success_div';
            $msg['file'] = $image;
            $data = array();
            $tableName = Utils::setTablePrefix('organization_announcement_commment_images');
            $data['announcement_id'] = $objUserImageData->announcement_id;
            $data['comment_id'] = $objUserImageData->comment_id;
            $data['user_id'] = $objUserImageData->user_id;
            $data['image_file_id'] = $image_id;
            $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;
        }
        $msg['image_id'] = $announcement_comment_image_id;
        return $msg;
    }
    
     public static function postComments($data_array,$cmnt='') {
        $db                         = new Db();
        $tableName                  = Utils::setTablePrefix('organization_announcement_comments');
        $comment_id                 = $db->insert($tableName, $data_array);
        if($data_array['parent_comment_id']>0){
            $res_announcement           = $db->selectRecord("organization_announcement_comments","num_replies","organization_announcement_comment_id=".$data_array['parent_comment_id']);
            $count                      = $res_announcement->num_replies+1;
            $rescomm                    = $db->updateFields("organization_announcement_comments", array('num_replies'=>$count),"organization_announcement_comment_id=".$data_array['parent_comment_id']);
            $return_array               = array('comment'=>$cmnt,'count'=>$count.' Replies','comment_id'=>$comment_id,'announcement_id'=>$data_array['announcement_id']);
        }
        else{
            $res_announcement           = $db->selectRecord("organization_announcements","organization_announcement_num_comments","organization_announcement_id=".$data_array['announcement_id']);
            $count                      = $res_announcement->organization_announcement_num_comments+1;
            $rescomm                    = $db->updateFields("organization_announcements", array('organization_announcement_num_comments'=>$count),"organization_announcement_id=".$data_array['announcement_id']);
            $return_array               = array('comment'=>$cmnt,'count'=>$count.' Comments','comment_id'=>$comment_id,'announcement_id'=>$data_array['announcement_id']);
        }
            
        return $return_array;
 
    }
    
    public static function UpdateCommentImage($data, $id) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('organization_announcement_commment_images');
        $tableNamefile = Utils::setTablePrefix('files');
        $where = "organization_announcement_image_id='" . $id . "'";
        //echopre($data);exit;
        //echo $id;exit;
        $image = $db->update($tableName, $data, $where, $doAudit = false);
        $query = "SELECT file_path from $tableNamefile where file_id IN(SELECT image_file_id from $tableName WHERE organization_announcement_image_id='" . $id . "')";
        //echo $query;exit;                      
        //Logger::info($query);
        $objResultRow = $db->fetchSingleRow($query);
//        echo $objResultRow->file_path;exit;
        // echo $objResultRow['file_path'];exit;
        return $objResultRow->file_path;
        // return $db->selectRecord($tableName,'file_path','file_id = "'.Utils::escapeString($emailAddress).'" '.$andCase );
    }
    
     public static function getAnnouncementComments($announcemnt_id,$pagenum=1,$itemsperpage=5) {
        $user_id            = Utils::getAuth('user_id');
        $db                 = new Db();
        $objResult          = new Messages();
        $objResult->status  = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($user_id != '') {
            $db                 = new Db();
            $users              = Utils::setTablePrefix('users');
            $business        = Utils::setTablePrefix('businesses');
            $likes              = Utils::setTablePrefix('organization_announcement_comments_like');
            $image              = Utils::setTablePrefix('organization_announcement_commment_images');
            $files              = Utils::setTablePrefix('files');
            $objUserData        = new stdClass();
            $objUserData->table = 'organization_announcement_comments C';
            $objUserData->key   = 'C.organization_announcement_comment_id';
            $objUserData->fields = "F.file_path,C.*,DATE_FORMAT(C.comment_date,'%m-%d-%Y %h:%i %p') AS commentDate,U.user_image_name,U.user_alias,CONCAT(U.user_firstname,' ',U.user_lastname) AS Username,cm.business_created_by ,(SELECT organization_announcement_comment_like_id  
                                               FROM ".$likes." l WHERE l.user_id=".$user_id." 
                                               AND l.comment_id = C.organization_announcement_comment_id 
                                               AND comment_like='1') AS LIKE_ID ";
            $objUserData->join   = " LEFT JOIN $image I ON I.comment_id = C.organization_announcement_comment_id LEFT JOIN $files F ON F.file_id = I.image_file_id  LEFT JOIN  $users U ON U.user_id = C.user_id  LEFT JOIN  $business AS cm ON cm.business_id = C.organization_id ";
            $objUserData->where  = "  C.announcement_id = $announcemnt_id AND parent_comment_id=0 ";
            
            $objUserData->groupbyfield = '';
            $objUserData->orderby       = 'DESC';
            $objUserData->orderfield    = 'C.comment_date';
            $objUserData->itemperpage   = $itemsperpage;
            $objUserData->page          = $pagenum;  // by default its 1
            $objUserData->debug         = true;
            $users1                      = $db->getData($objUserData);
          //  echopre1($users1);
            return $users1;
        }
    }
    
    public static function showCommentReply($comment_id,$pagenum=1,$itemsperpage=5){
        $user_id            = Utils::getAuth('user_id');
        $db                 = new Db();
        $objResult          = new Messages();
        $objResult->status  = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($user_id != '') {
            $db                 = new Db();
            $users              = Utils::setTablePrefix('users');
            $file               = Utils::setTablePrefix('files');
            $comment_image      = Utils::setTablePrefix('organization_announcement_commment_images');
            $businesses        = Utils::setTablePrefix('businesses');
            $objUserData        = new stdClass();
            $objUserData->table = 'organization_announcement_comments C';
            $objUserData->key   = 'C.organization_announcement_comment_id';
            $objUserData->fields = "C.*,DATE_FORMAT(C.comment_date,'%m-%d-%Y %h:%i %p') AS commentDate,U.user_image_name,U.user_alias, F.file_path,cm.business_created_by ";
            $objUserData->join   = " LEFT JOIN  $users U ON U.user_id = C.user_id LEFT JOIN $comment_image A ON A.comment_id = C.organization_announcement_comment_id"
                                    . " LEFT JOIN $file F ON A.image_file_id = F.file_id LEFT JOIN $businesses AS cm ON cm.business_id = C.organization_id";
            $objUserData->where  = " parent_comment_id='".$comment_id."'";
            
            $objUserData->groupbyfield = '';
            $objUserData->orderby       = 'DESC';
            $objUserData->orderfield    = 'C.comment_date';
            $objUserData->itemperpage   = $itemsperpage;
            $objUserData->page          = $pagenum;  // by default its 1
            $objUserData->debug         = true;
            $users1                      = $db->getData($objUserData);
            //echopre($users1);exit;
            return $users1;
    }
    }
    
    public static function postCommentLike($data){
        $db                         = new Db();
        $userId                     = Utils::getAuth('user_id');
        $tableName                  = Utils::setTablePrefix('organization_announcement_comments_like');
        $res                        = $db->selectRecord("organization_announcement_comments_like","*","comment_id=".$data['comment_id']." AND user_id=".$userId);
        $res_comment                = $db->selectRecord("organization_announcement_comments","num_comment_likes","organization_announcement_comment_id=".$data['comment_id']);
        //echopre($res_comment);
        if($res->organization_announcement_comment_like_id>0){
           
            
            $data_array                          = array();
            $data_array['comment_like']          = ($res->comment_like==1)?0:1;
            $return                              = ($res->comment_like==1)?'':'liked';
            $res1                                = $db->updateFields("organization_announcement_comments_like", $data_array,"comment_id=".$data['comment_id']." AND user_id=".$userId);
            if($data_array['comment_like']==0){ 
                $count                              = $res_comment->num_comment_likes-1;
            }
            else{
                $count                              = $res_comment->num_comment_likes+1;
            }
             $rescomm                                = $db->updateFields("organization_announcement_comments", array('num_comment_likes'=>$count),"organization_announcement_comment_id=".$data['comment_id']);
             $count                                  = ($count>0)?($count.' '.($count==1?'Like':'Likes')):'';
            $return_array                           = array('classtype'=>$return,'count'=>$count);
            print json_encode($return_array);
            exit;
            
        }
        else{
            
            $data['comment_like']                   = '1';
            $communityId                            = $db->insert($tableName, $data);
            $count                                  = ($res_comment->num_comment_likes > 0)?($res_comment->num_comment_likes+1):1;

            $rescomm                                = $db->updateFields("organization_announcement_comments", array('num_comment_likes'=>$count),"organization_announcement_comment_id=".$data['comment_id']);
            $return                                 = 'liked';
            $count                                  = ($count>0)?($count.' '.($count==1?'Like':'Likes')):'';

            $return_array                           = array('classtype'=>$return,'count'=>$count);
            print json_encode($return_array);
            exit;
            
        }
    }
    
    public static function deleteOrgFeeds($announcement_id) {
        $db                         = new Db();
        $rescomm                    = $db->updateFields("organization_announcements", array('organization_announcement_status'=>'D'),"organization_announcement_id=".$announcement_id);
        echo  $rescomm;
    }
    
    public static function deleteOrgComments($comment_id,$announcement_id) {
        $db                         = new Db();
        $tableName                  = Utils::setTablePrefix('organization_announcement_comments');
        $rescomm                    = $db->deleteRecord("organization_announcement_comments",'organization_announcement_comment_id ='.$comment_id );
        
        $res_announcement           = $db->selectRecord("organization_announcements","organization_announcement_num_comments","organization_announcement_id=".$announcement_id);
        if($res_announcement->organization_announcement_num_comments <=0){
            $count=0;
        }
        else{
            $count                      = $res_announcement->organization_announcement_num_comments-1;
        }
        $rescomm                    = $db->updateFields("organization_announcements", array('organization_announcement_num_comments'=>$count),"organization_announcement_id=".$announcement_id);
        echo  $count;
    }
    
    public static function getAllBusinessForUser($orderfield='business_created_on',$orderby='DESC',$pagenum=1,$itemperpage=5,$search='',$searchFieldArray,$userId='',$groupby,$from = '') {
  
        $db = new Db();
        
         $files                      =   Utils::setTablePrefix('files');
         
         $users                      =   Utils::setTablePrefix('users');
         $categories                      =   Utils::setTablePrefix('categories');
          $tagged                      =   Utils::setTablePrefix('tagged_business');
         $userId                     = Utils::getAuth('user_id');
         if($userId >0 )
         {
            
               $userWhere = " b.business_status != 'D' AND T.user_id = '".$userId."' ";
         }else{
             $userWhere = " b.business_status != 'D'";
         }
         if($groupby){
           $userWhere .= ' AND b.business_category_id = '.$groupby;
        }
        $objLeadData                = new stdClass();
        $objLeadData->table         = 'businesses AS b';
        $objLeadData->key           = 'b.business_id';
        $objLeadData->fields	    = 'b.*,f.*,T.business_id,u.user_firstname,u.user_lastname,c.category_name';
        $objLeadData->join	    = "LEFT JOIN $categories AS c ON c.category_id = b.business_category_id LEFT JOIN $files AS f ON b.business_image_id= f.file_id LEFT JOIN $users as u ON b.business_created_by = u.user_id LEFT JOIN $tagged T ON b.business_id = T.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 = '';  
        $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);exit;
        //return $leads->records;
        return $leads;
    }

    public static function updateOrgProfilePic($objOrgImageData,$width, $height) {
        
        $db = new Db();
        $table = 'businesses';
        $dataArray = array();
        $msg = array();
        try {
            $fileHandler = new Filehandler();
            $emailLogoFileDetails = $fileHandler->handleUpload($_FILES['file']);
            $image_id = $emailLogoFileDetails->file_id;
            $image = $emailLogoFileDetails->file_path;
            //echo FILE_UPLOAD_DIR;exit;

            if(!file_exists(FILE_UPLOAD_DIR."medium"))
                mkdir(FILE_UPLOAD_DIR."medium", 0777);

            if(!file_exists(FILE_UPLOAD_DIR."small"))
                mkdir(FILE_UPLOAD_DIR."small", 0777);

            if(!file_exists(FILE_UPLOAD_DIR."thumb"))
                mkdir(FILE_UPLOAD_DIR."thumb", 0777);

            if($width >= 178 || $height >= 164){
                Utils::allResize($image, 'medium', '', 164);
                Utils::allResize($image, 'small', '', 75);
                Utils::allResize($image, 'thumb', '', 50);
            }
            else{
                Utils::allResize($image, 'medium', $width, $height);
                //Utils::allResize($image, 'small', $width, $height);
                if($width >= 75 || $height >= 75){
                    Utils::allResize($image, 'small', '', 75);

                }
                else{
                    Utils::allResize($image, 'small', $width, $height);
                }
                if($width >= 50 || $height >= 50){
                    Utils::allResize($image, 'thumb', '', 50);

                }
                else{
                    Utils::allResize($image, 'thumb', $width, $height);
                }
            }

//            Utils::allResize($image, 'medium', 178, 164);
//            Utils::allResize($image, 'small', 75, 75);
//            Utils::allResize($image, 'thumb', 50, 50);
            $dataArray['business_image_id'] = $image_id;
//            $dataArray['org_image_id'] = ;
            $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'business_id="' . mysql_real_escape_string($objOrgImageData->business_id) . '"');
            $msg['msg'] = "Organization profile image changed";
            $msg['msgcls'] = 'success_div';
            $msg['file'] = $image;
        } catch (Exception $e) {
            $msg['msg'] = $e->getMessage();
            $msg['msgcls'] = 'error_div';
        }
        return $msg;
    }
    
   public static function getTaggedId($business_id){
       $db = new Db();
       $userId                     = Utils::getAuth('user_id');
       $res_tagged           = $db->selectRecord("tagged_business","tagg_id","business_id=".$business_id." AND user_id=".$userId);
       return $res_tagged;
    }
    
    public static function getMyLatestDiscussionImage($organization_id){
        //if($id){
        $db                             = new Db();
        //$userId                         = $_POST['uid'];
        $tableName                      = Utils::setTablePrefix('organization_announcements');
        $query                          = "SELECT c.* FROM ".$tableName." AS c  WHERE c.organization_id='".$organization_id."' AND c.organization_announcement_image_path !='' AND organization_announcement_status = 'A' ORDER BY c.organization_announcement_id DESC LIMIT 0,3";
        $objResultRow = $db->selectQuery($query);
        return $objResultRow;
       // }
    }
    
    public static function getOrganizationCommentsLikesUsers($id){
        if($id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('organization_announcement_likes');
//        $tableName1                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT user_name FROM ".$tableName." AS c  WHERE c.announcement_id=$id";
       // echo $query; exit;
        $objResultRow = $db->fetchAll($db->execute($query));
        return $objResultRow;
        }
    }
    
    public static function showOrgCommentOfCommentsLikeUser($id){
        if($id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('organization_announcement_comments_like');
//        $tableName1                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT user_name FROM ".$tableName." AS c  WHERE c.comment_id=$id";
       // echo $query; exit;
        $objResultRow = $db->fetchAll($db->execute($query));
        return $objResultRow;
        }
    }
    
    public static function showGrpCommentOfCommentsLikeUser($id){
        if($id){
        $db                             = new Db();
       // $userId                         = Utils::getAuth('user_id');
        $tableName                      = Utils::setTablePrefix('announcement_comments_like');
//        $tableName1                      = Utils::setTablePrefix('communities');
        $query                          = "SELECT user_name FROM ".$tableName." AS c  WHERE c.comment_id=$id";
       // echo $query; exit;
        $objResultRow = $db->fetchAll($db->execute($query));
        return $objResultRow;
        }
    }
}

?>