<?php

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

class User {
    /*
      Function to Register a  new User
     */

    public static function createUser($objUserVo) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        // echopre1($objUserVo);
        if ($objUserVo->user_email == '') {
            $objResult->status = ERROR;
        } else {
            //Check Entered User Email Exists OR NOT then stop user sign up if email exists
            $objUserEmailCount = self::checkUserEmailExists($objUserVo->user_email);
        }
        // echopre1($objUserEmailCount);
        if ($objUserEmailCount > 0) {
            $objResult->status = ERROR;
            $objResult->message = USER_EMAIL_EXIST; // Email Alreday Exists
        }
        
        // Insert User data to to User table 
        if ($objResult->status == SUCCESS) {
            $db = new Db();
            $tableName = Utils::setTablePrefix('users');

            $excludeId = '';
            $data = array();

            $data = Utils::objectToArray($objUserVo); //Convert Object To Array

            $email = explode('@', $objUserVo->user_email); //To get only first part of name
            $UserAliasName = Utils::generateAlias($tableName, $email[0], $idColumn = "user_id", $id = $excludeId, $aliasColumn = "user_alias");
            $data['user_alias'] = $UserAliasName;
            if ($objUserVo->user_firstname == '') {
                $data['user_firstname'] = $email[0];
            }

            $customerId = $db->insert($tableName, $data);
            $objUserVo->user_id = $customerId;
            $objUserVo->user_alias = $data['user_alias'];
            $objUserVo->user_firstname = $data['user_firstname'];
            $objUserVo->user_lastname = $data['user_lastname'];
            $objUserVo->user_imagename = $data['user_imagename'];
            $objResult->data = $objUserVo;
        }
        //echopre1($objUserVo);
        Logger::info($objResult);
        return $objResult;
    }

    /*
      Function to edit user profile information
     * Parameter -  User Data
     */

    public function editUser($userId = '', $objUserVo = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;

        //Check Entered User Email Exists OR NOT then stop user sign up if email exists
        $objUserEmailCount = self::checkUserEmailExists($objUserVo->user_email, $userId);
        //echo $objUserEmailCount;exit; 

        if ($objUserEmailCount) {
            $objResult->status = ERROR;
            $objResult->message = USER_EMAIL_EXIST; // Email Alreday Exists
        }


        // Update User data to  User table 

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



            $db = new Db();
            $data = array();

            $data = Utils::objectToArray($objUserVo);
            $tableName = Utils::setTablePrefix('users');
            $where = "user_id = " . Utils::escapeString($userId) . " ";
            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
            $objUserVo->user_id = $userId;
            $objResult->data = $objUserVo;
        }

        Logger::info($objResult);

        return $objResult;
    }

    /*
      Function to check  Customer email address already exists
     */

    public static function checkUserEmailExists($emailAddress, $customerId = '') {
        //echo $emailAddress;exit;
        $tableName = 'users';

        $db = new db();

        if ($customerId)
            $andCase = ' AND user_id !="' . Utils::escapeString($customerId) . '"';
        // echo 'user_email = "'.Utils::escapeString($emailAddress).'" '.$andCase;
        $result = $db->selectRow($tableName, 'count(user_id)', "user_email = '" . Utils::escapeString($emailAddress) . "' AND user_status != 'D' " . $andCase);
        //echopre($result);
        return $result;
    }

    /*
      Function to check  Customer email address already exists
     */

    public static function getUserEmailDetails($emailAddress, $customerId = '') {
        $tableName = 'users';

        $db = new db();

        if ($customerId)
            $andCase = ' AND user_id !="' . Utils::escapeString($customerId) . '"';

        return $db->selectRecord($tableName, '*', 'user_email = "' . Utils::escapeString($emailAddress) . '" ' . $andCase);
    }

    /*
      Function to check Customer User name alreday exists
     */

    public static function checkUserNameExists($userName, $customerId = '') {
        $tableName = 'users';

        $db = new db();

        if ($customerId > 0)
            $andCase = ' AND user_id !="' . Utils::escapeString($customerId) . '"';

        return $db->selectRow($tableName, 'user_id', 'user_name = "' . Utils::escapeString($userName) . '" ' . $andCase);
    }

    /*
      Function to check  Customer already exists in the system with the given user id
     */

    public static function checkUserExists($customerId = '') {
        $tableName = 'users';

        $db = new db();

        if ($customerId > 0)
            $andCase = "  user_id =" . Utils::escapeString($customerId) . "  ";

        return $db->selectRow($tableName, "*", $andCase);
    }

    /*
      Function to check  logged customer is approved
     */

    public static function checkUserPublished($customerId = '') {
        $tableName = 'users';

        $db = new db();

        if ($customerId > 0)
            $andCase = "  user_id =" . Utils::escapeString($customerId) . "  ";

        return $db->selectRow($tableName, "user_status", $andCase);
    }

    public static function fbLoginUser($userEmail) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;

        $db = new Db();
        $tableName = 'users';
        $selectCase = '(user_email ="' . Utils::escapeString($userEmail) . '") AND user_status != "D"';
        $objResultRow = $db->selectRecord($tableName, 'user_id,user_firstname,user_lastname,user_email,user_image_id,user_image_name,user_alias,user_status,user_country,user_reset_password,user_last_login', $selectCase);

        if ($objResultRow) {
            if ($objResultRow->user_status == 'D') {
                $objResult->status = ERROR;
                $objResult->message = USER_NOT_PUBLISHED; // User Not published 
            }
            $objResult->data = $objResultRow;
        } else {
            $objResult->status = ERROR;
            $objResult->message = USER_NOT_EXIST; // Username credentials invalid 
        }

        return $objResult;
    }

    public static function setUserOnlineStatus($userID, $status = 'Offline') {
        $db = new Db();
        $tableName = 'users';

        $curr_time = date("Y-m-d H:i:s");
        $where = "user_id='" . Utils::escapeString($userID) . "' ";
        $db->update(Utils::setTablePrefix($tableName), array('user_online_status' => $status, 'user_last_activity' => $curr_time), $where, false);

        return true;
    }
    
    /*
     * Log out users who havent signed out
     */
    public static function updateUserOnlineStatus() {
        $db = new Db();
        $tableName = 'users';

        $validTime = date('Y-m-d H:i:s', strtotime('-30 minutes'));        
        $where = "user_last_activity >= '" . $validTime . "' AND user_online_status = 'Online'";
        $objResultRow = $db->selectRecord($tableName, 'user_id', $where);
        
        if ($objResultRow) {
            foreach($objResultRow as $objResultEntity) {
                $where = "user_id='" . $objResultEntity->user_id . "' ";
                $db->update(Utils::setTablePrefix($tableName), array('user_online_status' => 'Offline'), $where, false);
            }
        }
        
        return true;
    }

    /*
      Function to check Customer Exists or not if exists re-direct to login
     * Parameters  : Username , Email Address , Password
     */

    public static function loginUser($objUserVo) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;

        //Check Entered User Email Exists OR NOT then prevent user  to login  to the system
        if ($objUserVo->user_email != '') {
            $objUserEmailCount = self::checkUserEmailExists($objUserVo->user_email);
            if ($objUserEmailCount <= 0) {
                $objResult->status = ERROR;
                $objResult->message = USER_EMAIL_NOT_EXIST; // Email Alreday Exists
            }
        }
        //  Check Entered User name not  Exists then prevent user  to login  to the system
        // User Login Check with email addreess and User name Combination 
        if ($objResult->status == SUCCESS) {

            $db = new Db();
            $tableName = 'users';
            $selectCase = '(user_email ="' . Utils::escapeString($objUserVo->user_email) . '") AND user_password="' . Utils::escapeString(md5($objUserVo->user_password)) . '" AND user_status!="D"';

            //$objResultRow                   =  $db->selectRecord($tableName,'user_id,user_firstname,user_lastname,user_email,user_image_id,user_image_name,user_alias,user_country',$selectCase);
            $objResultRow = $db->selectRecord($tableName, 'user_id,user_firstname,user_lastname,user_email,user_image_id,user_image_name,user_alias,user_status,user_country,user_reset_password,user_last_login', $selectCase);
            $objUserRes = new stdClass();
            $objUserRes->last_login = $objResultRow->user_last_login;
            // $_SESSION['user_last_login']    =  $objResultRow->user_last_login;
            Utils::setSessions($objUserRes);
            //echopre1($objResultRow);
            //Check User Status Published OR NOT 
            if ($objResultRow) {
                if ($objResultRow->user_status == 'D') {
                    $objResult->status = ERROR;
                    $objResult->message = USER_NOT_PUBLISHED; // User Not published 
                } else {  // If published assign user values to result object

                    $objResult->data = $objResultRow;
                    $where = "user_id='" . Utils::escapeString($objResultRow->user_id) . "' ";
                    $resultRows = $db->update(Utils::setTablePrefix('users'), array('user_last_login' => date('Y-m-d H:i:s') ), $where, $doAudit = false);
                    $objCookieVo = new stdClass();
//                    echo date('Y-m-d H:i:s');exit;
                    if ($objUserVo->remember_me == 1) { //Remember me
                        $objCookieVo->user_email = $objUserVo->user_email;
                        $objCookieVo->user_password = $objUserVo->user_password;
                        $expire = time() + 60 * 60 * 24 * 100;
                        Utils::setCookies($objCookieVo, $expire);
                    } else {
                        if (Utils::getCookies(user_email) != '') {
                            $objCookieVo->user_email = '';
                            $objCookieVo->user_password = '';
                            $past = time() - 100;
                            Utils::setCookies($objCookieVo, $past);
//                                setcookie(remember_me, gone, $past);
//                                Utils::setCookies($objCookieVo);
                        }
                    }
                    if ($objResultRow->user_reset_password == 'N') {
                        $objResult->status = SUCCESS;
                        $objResult->message = PASSWORD_RESET; // User Not published
                    }
                }
            }
            //User credentials invalid or User Not exists // return false
            else {

                $objResult->status = ERROR;
                $objResult->message = USER_NOT_EXIST; // Username credentials invalid 
            }
        }
        //Logger::info($objResult);
        return $objResult;
    }

    public static function adminLoginUser($objUserVo) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;

        //Check Entered User Email Exists OR NOT then prevent user  to login  to the system
        if ($objUserVo->user_email != '') {
            $objUserEmailCount = self::checkUserEmailExists($objUserVo->user_email);
            if ($objUserEmailCount <= 0) {
                $objResult->status = ERROR;
                $objResult->message = USER_EMAIL_NOT_EXIST; // Email Alreday Exists
            }
        }
        //  Check Entered User name not  Exists then prevent user  to login  to the system
        // User Login Check with email addreess and User name Combination
        if ($objResult->status == SUCCESS) {

            $db = new Db();
            $tableName = 'users';
            $selectCase = '(user_email ="' . Utils::escapeString($objUserVo->user_email) . '" AND user_status = "A")';

            $objResultRow = $db->selectRecord($tableName, 'user_id,user_firstname,user_lastname,user_email,user_image_id,user_alias', $selectCase);
            $objResultRow = $db->selectRecord($tableName, 'user_id,user_firstname,user_lastname,user_email,user_image_id,user_image_name,user_alias', $selectCase);

            //Check User Status Published OR NOT
            if ($objResultRow) {
                if ($objResultRow->user_status == 'I') {
                    $objResult->status = ERROR;
                    $objResult->message = USER_NOT_PUBLISHED; // User Not published
                } else {  // If published assign user values to result object
                    $objResult->data = $objResultRow;
                    $where = "user_id='" . Utils::escapeString($objResultRow->user_id) . "' ";
                    $resultRows = $db->update(Utils::setTablePrefix('users'), array('user_last_login' => date('Y-m-d H:i:s')
                            ), $where, $doAudit = false);
                    $objCookieVo = new stdClass();

                    if ($objUserVo->remember_me == 1) { //Remember me
                        $objCookieVo->user_email = $objUserVo->user_email;
                        $objCookieVo->user_password = $objUserVo->user_password;
                        Utils::setCookies($objCookieVo);
                    } else {
                        if (Utils::getCookies(user_email) != '') {
                            $objCookieVo->user_email = '';
                            $objCookieVo->user_password = '';
                            $past = time() - 100;
                            Utils::setCookies($objCookieVo, $past);
                            //                                setcookie(remember_me, gone, $past);
                            //                                Utils::setCookies($objCookieVo);
                        }
                    }
                }
            }
            //User credentials invalid or User Not exists // return false
            else {

                $objResult->status = ERROR;
                $objResult->message = USER_NOT_EXIST; // Username credentials invalid
            }
        }

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

    /*
      Function to check Customer Exists or not if exists re-direct to login
     * Parameters  : User Id 
     */

    public static function deleteUser($userId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //  Check Entered User Id  exists in the system
        if ($userId != '') {
            $objUserCount = self::checkUserExists($userId);
            if ($objUserCount > 0) {

                $objResult->status = SUCCESS;
            } else {
                $objResult->status = ERROR;
                $objResult->message = USER_ID_NOT_EXIST; // User Id not  Exists
            }
        }
        // Update User status to deleted  if user  already exists
        if ($objResult->status == SUCCESS) {

            $db = new Db();
            $tableName = Utils::setTablePrefix('users');
            $selectCase = '';
            $deleted = 'D';
            $where = "user_id='" . Utils::escapeString($userId) . "' ";
            $resultRows = $db->update($tableName, array('user_status' => Utils::escapeString($deleted),
                    ), $where, $doAudit = false);
            // Update  User Account with deleted status  and Set Corresponding Message
            if ($resultRows > 0) {
                $objResult->message = USER_DELETED_SUCCESS; // User Deleted Successfully
            }
        }

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

    /*
      Function to get user details
     * Parameters  : User id
     */

    public static function getUserDetails($alias) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($alias != '') {
            $db = new Db();

            $users = Utils::setTablePrefix('users');
            $files = Utils::setTablePrefix('files');
            //$industry = Utils::setTablePrefix('industry');
            $country = Utils::setTablePrefix('country');
            $state = Utils::setTablePrefix('state');

            $select = "SELECT user_id AS Id,  CONCAT(user_firstname,' ',user_lastname) AS Name, user_firstname,user_lastname,$users.user_country, file_path AS Image, user_image_name, user_email AS Email,   user_gender AS Gender , DATE_FORMAT(user_date_of_birth,'%m/%d/%Y') AS Date_of_Birth, user_address As Address,  user_city AS City,  $country.tc_name AS Country,$users.user_state AS State,$state.ts_name AS State1,  user_phone AS Phone,  user_zipcode AS Zip_Code, user_privacy AS User_Privacy,user_privacy,user_membership_type AS Membership_Type,  user_points AS Points, user_last_login,user_friends_count,user_community_count,user_business_count,user_friends_privacy 
                            FROM $users LEFT JOIN $files ON   $users.user_image_id = $files.file_id 
                            
                            LEFT JOIN $country ON $country.tc_code = $users.user_country  
                            LEFT JOIN $state ON $state.ts_code = $users.user_state
                            
                            WHERE user_alias = '" . $alias . "'";
//                 LEFT JOIN $state ON $state.ts_code = $users.user_state  AND  $state.tc_id=$country.tc_id   
            //echo $select;

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

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

    public static function getUserDetail($id) {
        // echo "here";exit;
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($id != 0) {
            $db = new Db();

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


            $select = "SELECT user_id AS Id,  CONCAT(user_firstname,' ',user_lastname) AS Name,user_alias, user_firstname,user_lastname, file_path AS Image, user_image_name, user_email AS Email,   user_gender AS Gender , DATE_FORMAT(user_date_of_birth,'%m/%d/%Y') AS Date_of_Birth, user_address As Address,  user_city AS City,  user_state AS State,  user_country AS Country,  user_phone AS Phone,  user_zipcode AS Zip_Code, user_membership_type AS Membership_Type,  user_points AS Points, user_last_login,user_friends_count,user_community_count,user_business_count,user_created_on FROM $users LEFT JOIN $files ON   $users.user_image_id = $files.file_id  WHERE user_id = " . $id;
            //echo $select;

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

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

    public static function getUserDetailId($id) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($id != 0) {
            $db = new Db();

            $users = Utils::setTablePrefix('users');
            	$files                      =   Utils::setTablePrefix('files');
            //	$industry                      =   Utils::setTablePrefix('industry');


            $select = "SELECT U.user_id, U.user_firstname,U.user_lastname, U.user_email,U.user_paypal_email,U.user_password,U.user_friends_privacy,U.user_status,"
                    . "U.user_alias,F.file_path as Image  FROM $users U LEFT JOIN $files F ON U.user_image_id = F.file_id WHERE U.user_id = " . $id;
            //echo $select;

            $objResultRow = $db->fetchSingleRow($select);
            // If user exists then assign user data to result object
            if ($objResultRow)
                $objResult->data = $objResultRow; // Assign user record  to object
            else {
                $objResult->status = ERROR;
                $objResult->message = USER_ID_NOT_EXIST; // User not exists
            }
        }
        $objResult->data->remember_me = 0;
        Logger::info($objResult);
        return $objResult;
    }

    /*
      Function to update user password
     * Parameters  : User value object , userId , new password
     */

    public static function updatePassword($objUserVo) {
        $db = new Db();
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $tableName = 'users';
        //Update User Password
        $userId = $db->selectRow($tableName, 'user_id', "user_password = '" . Utils::escapeString(md5($objUserVo->curpassword)) . "' AND user_id='" . $objUserVo->user_id . "'");

        //exit;
        if ($userId > 0) {
            $db = new Db();
            $tableName = Utils::setTablePrefix('users');
            $where = "user_id='" . Utils::escapeString($objUserVo->user_id) . "' ";
            $resultRows = $db->update($tableName, array('user_password' => Utils::escapeString(md5($objUserVo->newpassword)), 'user_reset_password' => 'Y'
                    ), $where, $doAudit = false);
            if ($resultRows > 0) {
                $objResult->message = USER_PASSWORD_UPDATED_SUCCESS; // User password changed successfully
                $objUserVo->password = $objUserVo->newpassword;
                $objResult->data = $objUserVo;
            } else {  // Reset password failed
                $objResult->status = ERROR;
                $objResult->message = USER_PASSWORD_UPDATED_FAILED;
            }
        } else {
            $objResult->status = ERROR;
            $objResult->message = USER_PASSWORD_WRONG;
        }

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

    /*
      Function to publish a user
     * Parameters  : User id , publishedStatus
     */

    public static function publishUser($userId, $publishedStatus) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        if ($userId != '') {
            //If User exists then activte a  User Account
            $db = new Db();
            $tableName = Utils::setTablePrefix('users');
            $where = "user_id='" . Utils::escapeString($userId) . "' ";
            $resultRows = $db->update($tableName, array('user_status' => Utils::escapeString($publishedStatus),
                    ), $where, $doAudit = false);
        }

        if ($resultRows > 0) {
            $objResult->message = USER_PUBLISHED_SUCCESS; // User Account published successfully
        } else {  // Reset password failed
            $objResult->status = ERROR;
            $objResult->message = USER_PUBLISHED_FAILURE;
        }

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

    /*
      Function to list All Users
     * Paramater : Table Delimeters
     */

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

        $objTableVo->tablename = 'users';
        $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 User Details exist 
        if ($objResultRows)
        // Assign User 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 update the password
     */

    public function updateUserPassword($objPassword) {
        $tableName = 'pwd_requests';
        $db = new db();
        $requestkey = $objPassword->resetkey;
        if ($requestkey != '') {
            // get the userid from the pwd reset key
            $userId = $db->selectRow($tableName, 'pr_userid', 'pr_key = "' . Utils::escapeString($requestkey) . '" ');
            if ($userId) { // valid activation key
                $objUserPwd = new stdClass();
                $objUserPwd->user_id = $userId;
                $objUserPwd->newpassword = $objPassword->password;
                $objResult = self::updatePassword($objUserPwd);
            } else {  // invalid activation key
                $objResult = new Messages();
                $objResult->status = ERROR;
                $objResult->message = PWD_RESET_INVALID_KEY;
            }
            return $objResult;
        }
    }

//    public static function updateUserRegisterTime($userId, $postedArray) {
//        $db = new Db();
//        $table = 'users';
//        $dataArray = array();
//
//        $data1 = $db->selectRecord($table, 'user_email,user_image_id', 'user_id = ' . $userId);
//        //echopre($data1);
//        //exit;
//        if ($data1->user_image_id > 0) {
//            $file = $db->selectRow('files', 'file_path', 'file_id = ' . $data1->user_image_id);
//            $dataArray['user_image_name'] = $file;
//            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($file, 'medium', 178, 164);
////            Utils::allResize($file, 'small', 75, 75);
////            Utils::allResize($file, 'thumb', 50, 50);
//        }
//        $email = explode('@', $data1->user_email); //To get only first part of name				
//        $userAliasName = Utils::generateAlias(MYSQL_TABLE_PREFIX . $table, $email[0], $idColumn = "user_id", $id = $excludeId, $aliasColumn = "user_alias");
//        $dataArray['user_alias'] = $userAliasName;
//        $dataArray['user_status'] = 'A';
//        $dataArray['user_created_on'] = date('Y-m-d H:i:s');
//        $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'user_id="' . mysql_real_escape_string($userId) . '"');
//        $mailIds = array();
//        $replaceparams = array();
//        $mailIds[$postedArray['user_email']] = '';
//        $replaceparams['FIRST_NAME'] = $postedArray['user_firstname'];
//        $replaceparams['LAST_NAME'] = $postedArray['user_lastname'];
//        $replaceparams['EMAIL'] = $postedArray['user_email'];
//        $replaceparams['PASSWORD'] = $postedArray['user_password'];
//        $objMailer = new Mailer();
//        $objMailer->sendMail($mailIds, 'admin_user_registration', $replaceparams);
//    }

//    public static function updateUserFile($userId) {
//        $db = new Db();
//        $table = 'users';
//        $dataArray = array();
//
//        $data = $db->selectRow($table, 'user_image_id', 'user_id = ' . $userId);
//        //echopre($data);
//        //exit;
//        $file = $db->selectRow('files', 'file_path', 'file_id = ' . $data);
//        $dataArray['user_image_name'] = $file;
//        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($file, 'medium', 178, 164);
////        Utils::allResize($file, 'small', 75, 75);
////        Utils::allResize($file, 'thumb', 50, 50);
//        $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'user_id="' . mysql_real_escape_string($userId) . '"');
//    }

    public static function updateAdminFile($admin_announcement_id) {
        $db = new Db();
        $table = 'admin_announcements';
        $dataArray = array();

        $data = $db->selectRow($table, 'admin_announcement_image_id', 'admin_announcement_id = ' . $admin_announcement_id);
        //echopre($data);
        //exit;
        $file = $db->selectRow('files', 'file_path', 'file_id = ' . $data);
        $dataArray['admin_announcement_image_name'] = $file;
        $dataArray['admin_announcement_created_date'] = date('Y-m-d');
        Utils::allResize($file, '', '', '');
        //Utils::allResize($file,'small',75,75);
        //Utils::allResize($file,'thumb',50,50);
        $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'admin_announcement_id="' . mysql_real_escape_string($admin_announcement_id) . '"');
    }

    /*
      Function to reset user password
     * Parameters  : User id
     */

    public static function resetPassword($userEmail) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Update User Password
        if ($userEmail != '') {
            $objUserDetails = self::getUserEmailDetails($userEmail);
            //If User exists then reset User password
            if ($objUserDetails) {
                $db = new Db();
                $newPassword = Utils::generateRandomPassword();
                $tableName = Utils::setTablePrefix('users');
                $where = "user_email='" . Utils::escapeString($userEmail) . "' ";
                $resultRows = $db->update($tableName, array('user_password' => Utils::escapeString(md5($newPassword)), 'user_reset_password' => 'N',), $where, $doAudit = false);

                if ($resultRows > 0) {
                    $objResult->message = USER_PASSWORD_RESETTED_SUCCESS; // User password reset successfully
                    $objResult->password = $newPassword;
                    $objResult->email = $userEmail;
                    $objResult->status = SUCCESS;
                    $objResult->data = $objUserDetails;
                } else {  // Reset password failed
                    $objResult->status = ERROR;
                    $objResult->message = USER_PASSWORD_RESETTED_FAILED;
                }
            } else {
                $objResult->status = ERROR;
                $objResult->message = USER_ID_NOT_EXIST; // User not exists
            }
        }

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

    public static function getState($user_id = '') {


        $tableName = 'users';

        $db = new Db();

        if ($user_id > 0)
            $andCase = "  user_id =" . Utils::escapeString($user_id) . "  ";

        $result = $db->selectRow($tableName, "user_state", $andCase);
        //print_r($result);
        Logger::info($result);
        return $result;
    }

    public static function getUserFriends($alias, $fields = 'users.*',$limit = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($alias != '') {

            $db = new Db();
            $user_id = self::getUserIdFromAlias($alias);
            $users = Utils::setTablePrefix('users');
            $friends_list = Utils::setTablePrefix('friends_list');
            $files = Utils::setTablePrefix('files');
            if($limit !=''){
              $limits = " LIMIT 0,$limit " ; 
            }
            $query = " SELECT $fields,friends.friends_list_view_status,files.file_path  
                                    FROM $friends_list friends 
                                    INNER JOIN $users users ON friends.friends_list_friend_id = users.user_id AND users.user_status='A'  
                                    LEFT JOIN $files files ON users.user_image_id = files.file_id 
                                    WHERE friends.friends_list_user_id ='" . Utils::escapeString($user_id) . "' 
                                    AND  friends.friends_list_status='A' ORDER BY friends.friends_list_id DESC $limits";

            Logger::info($query);

            $objResultRow = $db->fetchAll($db->execute($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 = NO_FRIEND_EXIST; // Buisiness not exists
            }
        }

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

    public static function getUserFriends1($alias, $pagenum = 1, $itemperpage = 10, $search = '', $orderfield = 'users.user_firstname', $orderby = 'ASC', $groupby = 'All') {
        //echo $alias;exit;
        $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 ($alias != '') {
            $db = new Db();
            $user_id = self::getUserIdFromAlias($alias);
            //echo $user_id;exit;
            $users = Utils::setTablePrefix('users');
            $friends_list = Utils::setTablePrefix('friends_list');
            $files = Utils::setTablePrefix('files');
            $objUserData = new stdClass();
            $objUserData->table = 'friends_list friends';
            $objUserData->key = 'friends_list_id';
            $objUserData->fields = 'users.*,fl.*,friends.friends_list_view_status';
            $objUserData->join = "INNER JOIN $users users ON friends.friends_list_friend_id = users.user_id AND users.user_status='A' 
											LEFT JOIN $files fl ON users.user_image_id = fl.file_id";
            $objUserData->where = " friends.friends_list_user_id =" . Utils::escapeString($user_id) . "
                                    AND  friends.friends_list_status='A' ";

            if ($search) {
                $objUserData->where .=" AND (CONCAT(users.user_firstname,users.user_lastname) LIKE  '%$search%' OR users.user_email LIKE '%$search%') ";
            }
            if ($groupby == 'Personal') {
                $objUserData->where .= " AND friends.friends_list_view_status='P'";
            }
            if ($groupby == 'Business') {
                $objUserData->where .= " AND friends.friends_list_view_status='B'";
            }
            $objUserData->where;

            $objUserData->groupbyfield = '';
            $objUserData->orderby = $orderby;
            $objUserData->orderfield = $orderfield;
            if($itemperpage <> 'N.A') {
                $objUserData->itemperpage = $itemperpage;            
                $objUserData->page = $pagenum;  // by default its 1
            }
            $objUserData->debug = true;
            if($user_id){
            $users = $db->getData($objUserData);
            }
          //  echopre($users);exit;
            return $users;
        }
    }

    public static function getAllUsers($orderfield = 'user_firstname', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '') {
        $db = new Db();
        $objUserData = new stdClass();
        $objUserData->table = 'users AS users';
        $objUserData->key = 'user_id';
        $objUserData->fields = '*';
        $objUserData->where = "user_status = 'A' ";

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

    public static function updateUserProfilePic($objUserImageData,$width, $height) {
        $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;
            //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, 'medium', 178, 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['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;
        } catch (Exception $e) {
            $msg['msg'] = $e->getMessage();
            $msg['msgcls'] = 'error_div';
        }
        return $msg;
    }

    public static function getUserIdFromAlias($alias) {
        $db = new Db();
        return $user_id = $db->selectRow('users', 'user_id', "user_alias='" . mysql_real_escape_string($alias) . "'");
    }

    public static function getAliasFromUserId($id) {
        $db = new Db();
        return $user_alias = $db->selectRow('users', 'user_alias', "user_id='" . $id . "'");
    }

    public static function getUserNameFromAlias($alias) {
        $db = new Db();
        return $user_name = $db->selectRow('users', 'CONCAT(user_firstname," ",user_lastname) AS name', "user_alias='" . $alias . "'");
    }

    public static function updateUserFriendCount($id) {
        $db = new Db();
        $table = Utils::setTablePrefix('users');
        $friendlist = Utils::setTablePrefix('friends_list');
        $query1 = "SELECT COUNT(friends_list_id) AS cnt FROM $friendlist friends INNER JOIN $table users ON friends.friends_list_friend_id = users.user_id AND users.user_status='A' WHERE friends.friends_list_user_id =$id AND friends.friends_list_status='A'";
        $count = $db->selectQuery($query1);
        $query = "UPDATE " . $table . " SET user_friends_count = " . $count[0]->cnt . " WHERE user_id=$id";
        $db->customQuery($query);
    }

    public static function getUserProfileName($searchString) {

        $db = new Db();
        $users = Utils::setTablePrefix('users');
        $query = " SELECT CONCAT(user_firstname,' ',user_lastname) AS label  ,user_alias as value, user_image_name AS image,'user' AS type
                                    FROM $users 
                                    WHERE user_status ='A' AND user_firstname like '%" . $searchString . "%' limit 3";

        $objResultRow = $db->fetchAll($db->execute($query));
        Logger::info($objResultRow);
        //echopre($objResultRow);
        return $objResultRow;
    }

    public static function getUserMutualFriendsCount($user_id, $friend_id) {
        if ($friend_id != '' && $user_id != '') {
            $db = new Db();
            $friends_list = Utils::setTablePrefix('friends_list');
            $query = "SELECT count(friends_list_friend_id) AS count FROM $friends_list 
                                    WHERE friends_list_friend_id IN (
                                    SELECT friends_list_friend_id FROM $friends_list 
                                    WHERE friends_list_user_id=$user_id
                                    ) 
                                    AND  friends_list_user_id=$friend_id";
            //echo $query;
            $objResultRow = $db->fetchRow($db->execute($query));
            Logger::info($objResultRow);
            //echopre($objResultRow);
            return $objResultRow->count;
        }
    }

    public static function unfriend($user_id, $friend_id) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('friends_list');
        $user = Utils::setTablePrefix('users');
        $whereUser = "friends_list_user_id='" . $user_id . "'  AND friends_list_friend_id ='" . $friend_id . "'";
        $userResultRows = $db->update($tableName, array('friends_list_status' => 'D',
                ), $whereUser, $doAudit = false);
        Connections:: rejectStatus($user_id, $friend_id, 'U');

        $whereFriend = "friends_list_user_id='" . $friend_id . "'  AND friends_list_friend_id ='" . $user_id . "'";
        $friendResultRows = $db->update($tableName, array('friends_list_status' => 'D',
                ), $whereFriend, $doAudit = false);

        $userFriendCount = $db->selectRow('users', 'user_friends_count', "user_id='" . $user_id . "'");
        $whereUserCount = "user_id='" . $user_id . "'";
        $friendResultRows = $db->update($user, array('user_friends_count' => $userFriendCount - 1,
                ), $whereUserCount, $doAudit = false);

        $friendsFriendCount = $db->selectRow('users', 'user_friends_count', "user_id='" . $friend_id . "'");
        $whereUserCount = "user_id='" . $friend_id . "'";
        $friendResultRows = $db->update($user, array('user_friends_count' => $friendsFriendCount - 1,
                ), $whereUserCount, $doAudit = false);
    }

    public static function getFriendInviationCheck($userId, $suggessioId) {

        $db = new Db();
        return $user_name = $db->selectRow('invitation', '*', "(invitation_sender_id='" . $userId . "' AND invitation_receiver_id = '" . $suggessioId . "' AND invitation_status!='D' AND invitation_entity = 'U') OR (invitation_receiver_id='" . $userId . "' AND invitation_sender_id = '" . $suggessioId . "' AND invitation_status!='D' AND invitation_entity = 'U') ");
    }

    public static function getFriendCheck($userId, $suggessioId) {

        $db = new Db();
        return $user_name = $db->selectRow('friends_list', '*', "friends_list_user_id='" . $userId . "' AND friends_list_friend_id = '" . $suggessioId . "' AND friends_list_status!='D'");
    }

    

    public static function getAssociatedBusiness($userId, $pagenum = 1, $itemperpage = 10) {

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

        $business = Utils::setTablePrefix('businesses');
        $tagged = Utils::setTablePrefix('tagged_business');
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');
        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
        $limitStart = ($currentPage * $itemPerPage) - $itemPerPage;
        $limitEnd = $itemPerPage;
        if ($pagenum != 'All') {
            $limitVal = ' LIMIT ' . $limitStart . ',' . $limitEnd;
        } else {
            $limitVal = '';
        }

        $query = "SELECT T.*,B.*,F.* from $tagged T 
                           INNER JOIN $business B ON T.business_id = B.business_id
                           LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           WHERE business_status ='A' AND T.user_id = '" . Utils::escapeString($userId) . "' ORDER BY T.tagg_id DESC " . $limitVal;
        //  echo $query;exit;  

        Logger::info($query);

        $objResultRow = $db->fetchAll($db->execute($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 getAssociatedBusinessByBusiness($businessId) {

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $db = new Db();
        $business = Utils::setTablePrefix('businesses');
        $tagged = Utils::setTablePrefix('tagged_business');
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');


        $query = "SELECT T.*,B.*,F.*,U.* from $tagged T 
                                            INNER JOIN $business B ON T.business_id = B.business_id 
                                            INNER JOIN  $users U ON U.user_id  = T.user_id    
                                            LEFT JOIN $files F ON U.user_image_id = F.file_id 
                                            WHERE  user_status ='A' 
                                            AND business_status ='A' 
                                            AND T.business_id = '" . Utils::escapeString($businessId) . "' 
                                            ORDER BY T.tagg_id DESC";


        Logger::info($query);

        $objResultRow = $db->fetchAll($db->execute($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 getAssociatedBusinessRow($tagg_id) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $db = new Db();

        $business = Utils::setTablePrefix('businesses');
        $tagged = Utils::setTablePrefix('tagged_business');
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');


        $query = "SELECT T.*,B.*,F.* from $tagged T 
                           INNER JOIN $business B ON T.business_id = B.business_id
                           LEFT JOIN $files F ON B.business_image_id = F.file_id 
                           WHERE business_status ='A' AND T.tagg_id = '" . Utils::escapeString($tagg_id) . "' ";


        Logger::info($query);

        $objResultRow = $db->fetchRow($db->execute($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 getAllAssociatesByBusiness($businessId, $pagenum = 1, $itemperpage = 10, $orderfield = 'tagg_id', $orderby = 'Desc', $search = '', $searchFieldArray) {

        $db = new Db();
        $business = Utils::setTablePrefix('businesses');
        $tagged = Utils::setTablePrefix('tagged_business');
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');



        $where = "user_status ='A' 
                                            AND business_status ='A' 
                                            AND T.business_id = '" . Utils::escapeString($businessId) . "' 
                                            ";




        $objLeadData = new stdClass();
        $objLeadData->table = 'tagged_business AS T';
        $objLeadData->key = 'T.tagg_id';
        $objLeadData->fields = 'T.*,B.*,F.*,U.*';
        $objLeadData->join = "INNER JOIN $business B ON T.business_id = B.business_id 
                                            INNER JOIN  $users U ON U.user_id  = T.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 getAllAffilateRequestByBusiness($business_id, $orderfield = 'business_affiliate_id', $orderby = 'Desc', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray) {

        $db = new Db();
        $business = Utils::setTablePrefix('businesses');
        $tagged = Utils::setTablePrefix('business_affiliates');
        $files = Utils::setTablePrefix('files');
        $users = Utils::setTablePrefix('users');


        $where = "business_affiliate_status='R' AND A.business_id=$business_id AND user_status ='A' 
                                            AND business_status ='A'
                                            ";




        $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 getMyCCStatus($user_id) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('users');
        $query = "SELECT user_token_id FROM " . $tableName . " WHERE user_id=" . $user_id;
        $objResultRow = $db->fetchSingleRow($query);
        if ($objResultRow->user_token_id != '') {
            return Y;
        } else {
            return N;
        }
    }

    public static function updateUserCCdetails($user_id, $token_id = 1) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('users');
        $where = "user_id='" . $user_id . "'";
        $friendResultRows = $db->update($tableName, array('user_token_id' => $token_id,
                ), $where, $doAudit = false);
    }

    public static function updateUserPaypalEmail($user_id, $data) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('users');
        $where = "user_id='" . $user_id . "'";
        $friendResultRows = $db->update($tableName, $data, $where, $doAudit = false);
    }

    public static function validateRegistration($formFields) {
        // $userobj       = new User();$userobj->createUser();

        $user_email = trim($formFields['user_emails']);
        $user_password = trim($formFields['user_passwords']);
        $user_confirm_password = trim($formFields['user_confirm_password']);
        $terms_conditions = isset($formFields['terms_conditions']) ? $formFields['terms_conditions'] : 0;
        $messages['error'] = 0;
        $messages['0'] = $messages['1'] = $messages['2'] = $messages['3'] = "";

        if ($user_email == "") {
            $messages['0'] = "Please enter email";
            $messages['error'] = 1;
        } else if ($messages['0'] == "") {
            if (!eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$', $user_email)) {
                $messages['0'] = "Please enter a valid email";
                $messages['error'] = 1;
            }

            if ($messages['0'] == "") {

                if ((self::checkUserEmailExists($user_email))) {
                    $messages['0'] = "User email already exists";
                    $messages['error'] = 1;
                }
            }
        }

        if ($user_password == "") {
            $messages['1'] = "Please enter password";
            $messages['error'] = 1;
        } else if ($messages['1'] == "") {
            if (strlen($user_password) < 8) {
                $messages['1'] = "Please enter at least 8 characters";
                $messages['error'] = 1;
            }

            if ($messages['1'] == "" && !preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/', $user_password)) {
                $messages['1'] = "Please enter a password with an uppercase character and a numeric.";
                $messages['error'] = 1;
            }
        }

        if ($user_confirm_password == "") {
            $messages['2'] = "Please re-enter password";
            $messages['error'] = 1;
        } else if ($messages['2'] == "" && $user_password != "") {
            if ($user_password != $user_confirm_password) {
                $messages['2'] = "Password mismatch!";
                $messages['error'] = 1;
            }
        }

        if ($terms_conditions == "0") {
            $messages['3'] = "Please accept the terms and conditions.";
            $messages['error'] = 1;
        }

        return $messages;
    }

    public static function updateUserFriendPrivacy($user_id, $data) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('users');
        $where = "user_id='" . $user_id . "'";
        $friendprivacy = $db->update($tableName, $data, $where, $doAudit = false);
    }

    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('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;
        $msg['image'] = $image;
        return $msg;
    }

    public static function UpdateCommentImage($data, $id) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('announcement_commment_images');
        $tableNamefile = Utils::setTablePrefix('files');
        $where = "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 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 UpdateNewsfeedCommentImage($data, $id) {
        $db = new Db();
        $tableName = Utils::setTablePrefix('newsfeed_comment_images');
        $tableNamefile = Utils::setTablePrefix('files');
        $where = "newsfeed_comment_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 newsfeed_comment_image_file_id from $tableName WHERE newsfeed_comment_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 updateCommunityProfilePic($objUserImageData,$width, $height) {
        $db = new Db();
        $table = 'communities';
        $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['community_image_id'] = $image_id;
            $db->update(MYSQL_TABLE_PREFIX . $table, $dataArray, 'community_id="' . mysql_real_escape_string($objUserImageData->community_id) . '"');
            $msg['msg'] = 'Community profile picture changed..';
            $msg['msgcls'] = 'success_div';
            $msg['file'] = $image;
        } catch (Exception $e) {
            $msg['msg'] = $e->getMessage();
            $msg['msgcls'] = 'error_div';
        }
        return $msg;
    }

    public static function getUserMutualFriends($user_id, $session_id) {

        $db = new Db();
        $friends_list = Utils::setTablePrefix('friends_list');
        $user = Utils::setTablePrefix('users');
        $query = "SELECT distinct(concat(u.user_firstname, u.user_lastname)) as user_name,u.user_image_name,u.user_alias, f.friends_list_friend_id from $user as u  left join $friends_list as f
                                   ON u.user_id=f.friends_list_friend_id AND u.user_status='A' WHERE f.friends_list_friend_id IN (
                                    SELECT friends_list_friend_id FROM $friends_list 
                                    WHERE friends_list_user_id=$session_id
                                    ) 
                                    AND  f.friends_list_user_id=$user_id AND f.friends_list_status = 'A'";
        // echo $query;
        $objResultRow = $db->selectQuery($query);
        Logger::info($objResultRow);
        //echopre($objResultRow);
        return $objResultRow;
    }

    public static function getUserMutualFriendCount($user_id, $friend_id) {
        if ($user_id != '' && $friend_id != '') {
            $db = new Db();
            $friends_list = Utils::setTablePrefix('friends_list');
            $user = Utils::setTablePrefix('users');
            $query = "SELECT count(distinct(f.friends_list_friend_id)) AS count FROM $friends_list as f left join 
                                    $user as u ON u.user_id=f.friends_list_friend_id AND u.user_status='A'
                                    WHERE f.friends_list_friend_id IN (
                                    SELECT friends_list_friend_id FROM $friends_list 
                                    WHERE friends_list_user_id=$user_id
                                    ) 
                                    AND  f.friends_list_user_id=$friend_id AND f.friends_list_status = 'A'";
            //echo $query;
            $objResultRow = $db->fetchRow($db->execute($query));
            Logger::info($objResultRow);
            //echopre($objResultRow);
            return $objResultRow->count;
        }
    }

    public static function getFriendsCount($friend_id, $type = '') {

        $db = new Db();
        $friends_list = Utils::setTablePrefix('friends_list');
        $users = Utils::setTablePrefix('users');
        if ($type == 'B') {
            $where = " AND friends_list_view_status='B' ";
        } elseif ($type == 'P') {
            $where = " AND friends_list_view_status='P' ";
        } else {
            $where = '';
        }
        $query = " SELECT count(friends_list_friend_id) AS count  
                                    FROM $friends_list friends 
                                    INNER JOIN $users users ON friends.friends_list_friend_id = users.user_id AND users.user_status='A'  
                                    WHERE friends.friends_list_user_id ='" . Utils::escapeString($friend_id) . "' 
                                    AND  friends.friends_list_status='A' $where ORDER BY users.user_firstname";

        //echo $query;
        $objResultRow = $db->fetchRow($db->execute($query));
        Logger::info($objResultRow);
        //echopre($objResultRow);
        return $objResultRow->count;
    }

    public function getuserId($mail) {

        $tableName = 'invitation';
        $db = new db();
        return $db->selectRecord($tableName, 'invitation_sender_id', 'invitation_receiver_email = "' . Utils::escapeString($mail) . '" ');
    }

    public static function getFriendName($searchString) {

        $db = new Db();
        $user_id = Utils::getAuth('user_id');
        $users = Utils::setTablePrefix('users');
        $friends = Utils::setTablePrefix('friends_list');
        $query = " SELECT CONCAT(u.user_firstname,' ',u.user_lastname) AS label  ,u.user_id as value, u.user_image_name
                                    AS image,u.user_email AS mail,f.friends_list_status
                                    FROM $users AS u LEFT JOIN $friends AS f ON f.friends_list_friend_id
                                    = u.user_id AND f.friends_list_user_id = '$user_id' WHERE  u.user_status ='A' AND u.user_firstname like '%$searchString%' AND f.friends_list_status = 'A'   limit 5";
        //  echo $query;
        $objResultRow = $db->fetchAll($db->execute($query));
        Logger::info($objResultRow);
        //echopre($objResultRow);
        return $objResultRow;
    }

    public static function changeStatus($data, $id) {
        $db = new Db();
        //  $data = array();
        $userId = Utils::getAuth('user_id');
        // $data = Utils::objectToArray($objUserVo); 
        $tableName = Utils::setTablePrefix('friends_list');
        $where = "friends_list_user_id = " . Utils::escapeString($userId) . " AND  friends_list_friend_id =" . Utils::escapeString($id) . " AND friends_list_status='A'";
        $customerId = $db->update($tableName, $data, $where, $doAudit = false);
    }


    public static function addNewsfeedImage($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);
            //Utils::allResize($image, 'small', $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); 
            }
            
            
            }
            $dataArray['news_feed_image_name'] = $image;
            $dataArray['news_feed_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('news_feed');
            //$data['announcement_id']        = $objUserImageData->announcement_id;
             $AliasName = Utils::generateAlias($tableName, $data['news_feed_comment'], $idColumn = "news_feed_id", $id = $excludeId, $aliasColumn = "news_feed_alias");
            $data['news_feed_alias'] = $AliasName;
            $data['news_feed_user_name'] = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
            $data['news_feed_date'] = date('Y-m-d H:i:s');
            $data['news_feed_comment'] = $objUserImageData->news_feed_comment;
            $data['news_feed_user_id'] = $objUserImageData->news_feed_user_id;
            $data['news_feed_image_id'] = $image_id;
            $data['news_feed_image_name'] = $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 changeNewsfeedComment($data, $feedid) {
        $db = new Db();
        $userId = Utils::getAuth('user_id');
        $tableName = Utils::setTablePrefix('news_feed');
        $AliasName = Utils::generateAlias($tableName, $data['news_feed_comment'], $idColumn = "news_feed_id", $id = $excludeId, $aliasColumn = "news_feed_alias");
        $data['news_feed_alias'] = $AliasName;
        $data['news_feed_user_name'] = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
        $data['news_feed_date'] =  date('Y-m-d H:i:s');
        //  $data = array();
        // $userId                = Utils::getAuth('user_id');
        // $data = Utils::objectToArray($objUserVo); 
        // echopre1($data);
        //echo $feedid;exit;
        if ($feedid > 0) {
            $where = "news_feed_id = " . Utils::escapeString($feedid);
            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
        } else {
            $data['news_feed_user_id'] = $userId;
            $customerId = $db->insert($tableName, $data);
        }
        return $customerId;
    }
//     private static function compares($a, $b) {
//        // echo"here";exit;
//        $ad = new DateTime($a['news_feed_date']);
//        $bd = new DateTime($b['news_feed_date']);
//        if ($ad == $bd) {
//          return 0;
//        }
//
//        return $ad > $bd ? -1 : 1;
//}

    public function getTimeLine($userId,$pagenum = '',$itemperpage = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        //if ($alias != '') {
        //$userId = Utils::getAuth('user_id');
        $db = new Db();
        //$user_id = User::getUserIdFromAlias($alias);
        //$newsfeed = Utils::setTablePrefix('news_feed');
        $files = Utils::setTablePrefix('files');
            $newsfeed = Utils::setTablePrefix('news_feed');
            $friend = Utils::setTablePrefix('friends_list');
            $user = Utils::setTablePrefix('users');
            $date = date('Y-m-d H:i: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 ='';
                }
       
            
        //$query = " SELECT * FROM $newsfeed WHERE news_feed_user_id ='" . Utils::escapeString($userId) . "' ORDER BY news_feed_id DESC";
        $query = "SELECT n.*,DATEDIFF('$date',n.news_feed_date) as days,TIMEDIFF('$date',n.news_feed_date) AS output_time,u.user_image_name,u.user_alias,CONCAT(u.user_firstname,' ',u.user_lastname) AS Username,f.file_path   
                FROM $newsfeed AS n 
                LEFT JOIN $user AS u ON u.user_id = n.news_feed_user_id
                LEFT JOIN $files AS f ON u.user_image_id = f.file_id     
                WHERE n.news_feed_user_id = '".$userId."' ORDER BY n.news_feed_date DESC $limitVal";
        Logger::info($query);
        //$objResultRow = $db->fetchAll($db->execute($query));
          $objResultRow = $db->fetchAllArray($db->execute($query));
         //usort($objResultRow,array('User','compares') );
          
          // echopre1($objResultRow);
//            usort($objResultRow, function($a, $b) {
//                $ad = new DateTime($a['news_feed_date']);
//                $bd = new DateTime($b['news_feed_date']);
//
//                if ($ad == $bd) {
//                  return 0;
//                }
//
//                return $ad > $bd ? -1 : 1;
//            });

        // 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 = NO_FRIEND_EXIST; // Buisiness not exists
        }
        //  }

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

    public function getNewsFeedById($id) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        //if ($alias != '') {
        $userId = Utils::getAuth('user_id');
        $db = new Db();
        //$user_id = User::getUserIdFromAlias($alias);
        $newsfeed = Utils::setTablePrefix('news_feed');
        $user = Utils::setTablePrefix('users');
        
        //$invitation = Utils::setTablePrefix('invitation');

        $query = " SELECT n.*,u.user_image_name FROM $newsfeed AS n LEFT JOIN $user AS u ON u.user_id =n.news_feed_user_id WHERE n.news_feed_user_id ='" . Utils::escapeString($userId) . "' AND n.news_feed_id ='" . Utils::escapeString($id) . "'";
        Logger::info($query);
//echo $query;exit;
        $objResultRow = $db->fetchAll($db->execute($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 = NO_FRIEND_EXIST; // Buisiness not exists
        }
        //  }

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

     public function getNewsFeed($pagenum='',$itemperpage='',$userId) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        $date = date('Y-m-d H:i:s');
//        echo $date;
//        echo $date;exit;
        //Select Buisiness Record If Buisiness id is not null
        //if ($alias != '') {
        $userId                = $userId;
            $db = new Db();
            //$user_id = User::getUserIdFromAlias($alias);
            $newsfeed = Utils::setTablePrefix('news_feed');
            $friend = Utils::setTablePrefix('friends_list');
            $user = Utils::setTablePrefix('users');
            $files = Utils::setTablePrefix('files');
//            $date = date('Y-m-d H:i: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 ='';
                }
       
            $query = " SELECT * FROM
(SELECT n.*,DATEDIFF('$date',n.news_feed_date) as days,TIMEDIFF('$date',n.news_feed_date) AS output_time,u.user_image_name,u.user_alias,CONCAT(u.user_firstname,' ',u.user_lastname) AS Username,f.file_path   
                FROM $newsfeed AS n 
                LEFT JOIN $user AS u ON u.user_id = n.news_feed_user_id 
                LEFT JOIN $files as f ON f.file_id = u.user_image_id 
                WHERE n.news_feed_user_id = '".$userId."'
                UNION 
                SELECT n.*,DATEDIFF('$date',n.news_feed_date) as days,TIMEDIFF('$date',n.news_feed_date) AS output_time,u.user_image_name,u.user_alias,CONCAT(u.user_firstname,' ',u.user_lastname) AS Username,f.file_path    
                FROM $newsfeed AS n  LEFT JOIN $user AS u ON u.user_id = n.news_feed_user_id
                    LEFT JOIN $files as f ON f.file_id = u.user_image_id 
                WHERE n.news_feed_user_id IN(SELECT friends_list_friend_id FROM $friend WHERE friends_list_user_id ='".$userId."' AND friends_list_status='A')) $newsfeed ORDER BY news_feed_id DESC  $limitVal" ;
            
                                               Logger::info($query);
                                              // echo $query;
            $objResultRow = $db->fetchAllArray($db->execute($query));
         //  usort($objResultRow,array('User','compares') );
//            usort($objResultRow, function($a, $b) {
//                //return $a['news_feed_date'] - $b['news_feed_date'];
//                $ad = new DateTime($a['news_feed_date']);
//                $bd = new DateTime($b['news_feed_date']);
//
//                if ($ad == $bd) {
//                  return 0;
//                }
//
//                return $ad > $bd ? -1 : 1;
//            });
             //echopre($objResultRow);

            // 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 = NO_FEED_EXIST; // Buisiness not exists
            }
      //  }

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

    public static function addFeedCommentImage($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', 800, 480);
            Utils::allResize($image, 'small', 75, 75);
            Utils::allResize($image, 'thumb', 50, 50);
            }
            else{
            Utils::allResize($image, 'medium', $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, '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('newsfeed_comment_images');
            $data['newsfeed_id'] = $objUserImageData->newsfeed_id;
            $data['newsfeed_comment_id'] = $objUserImageData->newsfeed_comment_id;
            $data['user_id'] = $objUserImageData->user_id;
            $data['newsfeed_comment_image_file_id'] = $image_id;
            $data['newsfeed_comment_image_status'] = 'I';
            $data['newsfeed_comment_image_date'] = $objUserImageData->newsfeed_comment_image_date;
//echopre($data);exit;
            $newsfeed_comment_image_id = $db->insert($tableName, $data);
        } catch (Exception $e) {
            $msg['msg'] = $e->getMessage();
            $msg['msgcls'] = 'error_div';
            $msg['image_id'] = $newsfeed_comment_image_id;
        }
        $msg['image_id'] = $newsfeed_comment_image_id;
        return $msg;
    }
   public static function getUserTimelineImage($id)
 {  
    $objResult                        =   new Messages();
    $objResult->status                =   SUCCESS;
 //Select User Record If User id is not null
 if($id != '') {
 	$db                             =   new Db();
 
 	$users                      =   Utils::setTablePrefix('users');
 	$files                      =   Utils::setTablePrefix('files');
 	
 	 
 	 
 	$select = "SELECT user_timeline_image_name FROM $users WHERE user_alias = '".$id."'" ;
 	//echo $select;
 	 
 	$objResultRow                   =  $db->fetchSingleRow($select);
 	// If user exists then assign user data to result object
 	if($objResultRow)
 		$objResult->data           =   $objResultRow; // Assign user record  to object
 	else{
 		$objResult->status          =   ERROR;
 		$objResult->message         =   USER_ID_NOT_EXIST; // User not exists
 	}
 }
  Logger::info($objResult);
            return $objResult->data->user_timeline_image_name;
 } 
 
 
    public static function addGroupNewsfeedImage($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['community_announcement_image_path'] = $image;
            $dataArray['community_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('community_announcements');
            $data['community_id']        = $objUserImageData->community_id;
            $AliasName = Utils::generateAlias($tableName, $data['community_announcement_content'], $idColumn = "community_announcement_id", $id = $excludeId, $aliasColumn = "community_announcement_alias");
            $data['community_announcement_alias'] = $AliasName;
//            $data['news_feed_user_name'] = Utils::getAuth('user_firstname') . ' ' . Utils::getAuth('user_lastname');
            $data['community_announcement_date'] = date('Y-m-d H:i:s');
            $data['community_announcement_content'] = $objUserImageData->community_announcement_content;
            $data['community_announcement_user_id'] = $objUserImageData->community_announcement_user_id;
            $data['community_announcement_image_id'] = $image_id;
            $data['community_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 changeGroupfeedComment($data, $feedid) {
        $db = new Db();
        $userId = Utils::getAuth('user_id');
        $tableName = Utils::setTablePrefix('community_announcements');
        $AliasName = Utils::generateAlias($tableName, $data['community_announcement_content'], $idColumn = "community_announcement_id", $id = $excludeId, $aliasColumn = "community_announcement_alias");
        $data['community_announcement_alias'] = $AliasName;
        $data['community_announcement_date'] = date("Y-m-d H:i:s");

        if ($feedid > 0) {
            $where = "community_announcement_id = " . Utils::escapeString($feedid);
            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
        } else {
            $data['community_announcement_user_id'] = $userId;
            $customerId = $db->insert($tableName, $data);
        }
        return $customerId;
    }

}

?>
