<?php

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

class Connections {
    /*
      Function to Add a  new Invitation
     */

    public static function addInvitation($objConnectionsVo) {
        $objResult                          = new Messages();
        $objResult->status                  = SUCCESS;
        if ($objConnectionsEmailCount > 0) {
            $objResult->status              = "ERROR";
            $objResult->message             = GROUP_ID_NOT_EXIST;
        }
        if ($objResult->status == SUCCESS) {
            $db = new Db();
            $mailTemplate                       = $db->selectRecord("mail_template", "mail_template_status", "mail_template_name='" . $objConnectionsVo->mail_template . "'");
            //echopre1($mailTemplate);
            if ($mailTemplate->mail_template_status == 1) {
                $tableName1                     = Utils::setTablePrefix('users');
                $tableName                      = Utils::setTablePrefix('invitation');
                $excludeId                      = '';
                $customerId                     = $db->insert($tableName, array('invitation_type' => $db->escapeString($objConnectionsVo->invitation_type),
                                                            'invitation_entity' => $db->escapeString($objConnectionsVo->invitation_entity),
                                                            'invitation_entity_id' => $objConnectionsVo->invitation_entity_id,
                                                            'invitation_sender_email' => $db->escapeString($objConnectionsVo->invitation_sender_email),
                                                            'invitation_sender_id' => $objConnectionsVo->invitation_sender_id,
                                                            'invitation_receiver_email' => $db->escapeString($objConnectionsVo->invitation_receiver_email),
                                                            'invitation_receiver_id' => $objConnectionsVo->invitation_receiver_id,
                                                            'invitation_created_on' => date('Y-m-d H:i:s'),
                                                            'invitation_status' => $db->escapeString($objConnectionsVo->invitation_status)
                                                                ));
                $objResult->invitation_id       = $customerId;
                $objResult->data                = $objConnectionsVo;
                
                
            $where                          = '  user_id =' . $db->escapeString($objConnectionsVo->invitation_receiver_id);
            $frndcount                 = $db->selectRow('users', 'user_friend_request_count', $where);
            $frndcount++;
            $db->update($tableName1, array('user_friend_request_count' => $frndcount), $where, $doAudit = false);
            } else {
                $objResult->status              = ERROR;
            }
        }
        Logger::info($objResult);
        return $objResult;
    }

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

            $objResultRow = $db->selectRecord($tableName, '*', $selectCase);
            // 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 = GROUP_ID_NOT_EXIST; // User not exists
            }
        }

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

    public static function getPendingBizComrequest($userId, $page = 0, $limit = 4) {

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select User Record If User id is not null
        if ($userId != '') {
            $db = new Db();
            $invite = Utils::setTablePrefix('invitation');
            $community = Utils::setTablePrefix('communities');
            $users = Utils::setTablePrefix('users');
            $files = Utils::setTablePrefix('files');


            $query = "SELECT I.*,U.*,C.*,F.* FROM $invite I INNER JOIN $community C ON C.community_id = I.invitation_entity_id 
                    INNER JOIN  $users U ON U.user_id = I.invitation_sender_id
                    LEFT JOIN $files F ON C.community_image_id = F.file_id
                    WHERE I.invitation_receiver_id = '" . $db->escapeString($userId) . "' AND I.invitation_status = 'P' AND I.invitation_entity = 'C' LIMIT 0,4";


            //  echo $query;

            Logger::info($query);

            $objResultRow = $db->fetchAll($db->execute($query));

            // If user exists then assign user data to result object

            $objResult->data = $objResultRow; // Assign user record  to object
        } else {
            $objResult->status = "ERROR";
            $objResult->message = GROUP_ID_NOT_EXIST; // User not exists
        }

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

    /*
      Function to edit Invitation Status
     * Parameter -  Connections Data
     */

    public static function changeInvitationStatus($invitationId = '', $objConnectionsVo = '') {
        $objResult = new Messages();
        $objResult->status = SUCCESS;

        $data = array();
        if ($invitationId == '') {
            $objResult->status = "ERROR";
            $objResult->message = GROUP_ID_NOT_EXIST; // Email Alreday Exists
        }

        //echo $invitationId;
        // Update Connections data to  Connections table 
        // echopre($objConnectionsVo);
        if ($objResult->status == SUCCESS) {

            $db = new Db();

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


            $where = "invitation_id = " . $db->escapeString($invitationId) . " ";

            $data = Utils::objectToArray($objConnectionsVo);

            $customerId = $db->update($tableName, $data, $where, $doAudit = false);
            $objConnectionsVo->invitation_id = $invitationId;
            $objResult->data = $objConnectionsVo;
        }
        
        Logger::info($objResult);

        return $objResult;
    }

    public static function rejectStatus($reciever_id, $entity_id, $entity_type) {

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

        $data = array();
        if ($reciever_id == '') {
            $objResult->status = "ERROR";
            $objResult->message = GROUP_ID_NOT_EXIST; // Email Alreday Exists
        }

        //echo $invitationId;
        // Update Connections data to  Connections table 
        // echopre($objConnectionsVo);
        if ($objResult->status == SUCCESS) {

            $db = new Db();

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


            $where = "invitation_entity = '" . $db->escapeString($entity_type) . "' AND invitation_entity_id = " . $db->escapeString($entity_id) . " AND invitation_receiver_id = " . $db->escapeString($reciever_id) . " ";

            $data = Utils::objectToArray($objConnectionsVo);

            $customerId = $db->update($tableName, array('invitation_status' => 'DJ'), $where, $doAudit = false);
            $objConnectionsVo->invitation_id = $invitationId;
            $objResult->data = $objConnectionsVo;
        }

        Logger::info($objResult);

        return $objResult;
    }

    public static function acceptFriendRequest($invitationId, $objUserVo) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        if ($invitationId == '') {
            $objResult->status = "ERROR";
            $objResult->message = GROUP_ID_NOT_EXIST; // Email Alreday Exists
        }

        $invitationDetails = Connections::getInvitationDetails($invitationId);
        //echopre($invitationDetails);
        if ($objResult->status == SUCCESS) {

            if ($invitationDetails->data->invitation_status == 'A') {


                $db = new Db();

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

                $excludeId = '';

                $customerId = $db->insert($tableName, array('friends_list_user_id' => $objUserVo->friends_list_user_id,
                    'friends_list_friend_id' => $objUserVo->friends_list_friend_id,
                    'friends_list_status' => 'A',
                        ));

                $customerId = $db->insert($tableName, array('friends_list_user_id' => $objUserVo->friends_list_friend_id,
                    'friends_list_friend_id' => $objUserVo->friends_list_user_id,
                    'friends_list_status' => 'A',
                        ));

                $objConnectionsVo->friends_list_id = $customerId;
                $objResult->data = $invitationDetails;
            }
        }


        Logger::info($objResult);

        return $objResult;
    }

    public static function changeFriendStatus($user_id = '', $friendUserId = '', $objConnectionsVo) {

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        if ($user_id == '') {
            $objResult->status = "ERROR";
            $objResult->message = GROUP_ID_NOT_EXIST;
        }

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

            $db = new Db();

            $tableName = Utils::setTablePrefix('friends_list');
            $where = "friends_list_user_id = " . $db->escapeString($user_id) . " AND friends_list_friend_id = " . $db->escapeString($friendUserId) . " ";
            $customerId = $db->update($tableName, array('friends_list_status' => $db->escapeString($objConnectionsVo->friends_list_status),
                    ), $where, $doAudit = false);
            $where = "friends_list_user_id = " . $db->escapeString($friendUserId) . " AND friends_list_friend_id = " . $db->escapeString($user_id) . " ";
            $customerId = $db->update($tableName, array('friends_list_status' => $db->escapeString($objConnectionsVo->friends_list_status),
                    ), $where, $doAudit = false);


            $objConnectionsVo->invitation_id = $invitationId;
            $objResult->data = $objConnectionsVo;
        }

        Logger::info($objResult);

        return $objResult;
    }

    public static function acceptCommunityRequest($invitationId, $objMemVo) {

        $objResult = new Messages();
        $objResult->status = SUCCESS;
        if ($objMemVo->cmember_id == '' || $objMemVo->cmember_community_id == '') {

            $objResult->status = "ERROR";
            $objResult->message = COMMUNITY_ID_NOT_EXIST; // User Id not  Exists
        }


        $invitationDetails = Connections::getInvitationDetails($invitationId);

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

            $db = new Db();
            $tableName = Utils::setTablePrefix('community_member');
            $communityId = $db->insert($tableName, array('cmember_id' => $objMemVo->invitation_receiver_id,
                'cmember_community_id' => $objMemVo->invitation_entity_id,
                'cmember_type' => $db->escapeString($objMemVo->cmember_type),
                'cmember_joined_on' => $objMemVo->cmember_joined_on,
                //    'cmember_created_by'    =>  $objMemVo->cmember_created_by,
                'cmember_status' => $db->escapeString($objMemVo->cmember_status)
                    ));
            $objMemVo->cmember_list_id = $communityId;
            $objResult->data = $objMemVo;
        }

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

    public function getAllUserInvitationsSent($alias, $status = 'P', $fields) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($alias != '') {

            $db = new Db();
            $user_id = User::getUserIdFromAlias($alias);
            $table = Utils::setTablePrefix('invitation');

            $query = " SELECT $fields  
                                    FROM $table  
                                    WHERE invitation_entity_id ='" . $db->escapeString($user_id) . "' 
                                    AND  invitation_entity='U' AND  invitation_status='$status' AND invitation_type='U' ORDER BY invitation_id";


            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 function getUserPendingRequest($alias) {
        $objResult = new Messages();
        $objResult->status = SUCCESS;
        //Select Buisiness Record If Buisiness id is not null
        if ($alias != '') {

            $db = new Db();
            $user_id = User::getUserIdFromAlias($alias);
            $users = Utils::setTablePrefix('users');
            $invitation = Utils::setTablePrefix('invitation');

            $query = " SELECT users.*,invitation.invitation_id    
                                    FROM $invitation AS invitation 
				    LEFT JOIN  $users AS users ON users.user_id = invitation.invitation_entity_id AND users.user_status='A' 
                                    WHERE invitation_receiver_id ='" . $db->escapeString($user_id) . "' 
                                    AND  invitation_entity='U' AND invitation_status='P' AND invitation_type='U' ORDER BY invitation_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 = NO_FRIEND_EXIST; // Buisiness not exists
            }
        }

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

    public static function getAllPendingRequest($orderfield = 'invitation_created_on', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10,$search = '') {
//echo "here";exit;
        $user_id                    = Utils::getAuth('user_id');
        $objUserData                = new stdClass();
        $db                         = new Db();
        $users                      = Utils::setTablePrefix('users');
        $files                      = Utils::setTablePrefix('files');
          $where                          = '  user_id =' . $db->escapeString($db->escapeString($user_id));
            $frndcount                 = 0;
            $db->update($users, array('user_friend_request_count' => $frndcount), $where, $doAudit = false);
        $objUserData->table         = 'invitation AS invitation';
        $objUserData->key           = 'invitation_id';
        $objUserData->fields        = 'invitation.invitation_id,users.*,f.file_path';
        $objUserData->join          = " LEFT JOIN  $users AS users ON users.user_id = invitation.invitation_entity_id LEFT JOIN $files AS f ON users.user_image_id = f.file_id AND users.user_status='A' ";
        $objUserData->where         = " invitation_receiver_id ='" . $db->escapeString($user_id) . "' 
                                    	AND  invitation_entity='U' AND invitation_status='P' AND invitation_type='U'";
        $objUserData->where;
        if ($search) {
                    $objUserData->where .=" AND (CONCAT(users.user_firstname,users.user_lastname) LIKE  '%$search%' OR users.user_email LIKE '%$search%') ";
			}
        $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 getAllPendingRequestinbox($orderfield = 'invitation_created_on', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10) {

        $user_id                = Utils::getAuth('user_id');
        $objUserData            = new stdClass();
        $db                     = new Db();
        $users                  = Utils::setTablePrefix('users');
        $invite                 = Utils::setTablePrefix('invitation');
        $files                  = Utils::setTablePrefix('files');
        $community              = Utils::setTablePrefix('communities');




        $objUserData->table = 'invitation AS I';
        $objUserData->key = 'invitation_id';
        $objUserData->fields = 'I.*,U.*,C.*,F.*';
        $objUserData->join = "INNER JOIN $users U ON U.user_id = I.invitation_sender_id LEFT JOIN $community C ON C.community_id = I.invitation_entity_id LEFT JOIN $files F ON C.community_image_id = F.file_id";
        $objUserData->where = " I.invitation_receiver_id ='" . $db->escapeString($user_id) . "' 
                                    	AND I.invitation_status='P'";




        $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);
        //echopre($users);
        //return $leads->records;
        return $users;
    }

    public static function getAllPendingRequestinboxcount($orderfield = 'invitation_created_on', $orderby = 'ASC', $pagenum = 1, $itemperpage = '') {

        $user_id                    = Utils::getAuth('user_id');
        $objUserData                = new stdClass();
        $db                         = new Db();
        $users                      = Utils::setTablePrefix('users');
        $invite                     = Utils::setTablePrefix('invitation');
        $files                      = Utils::setTablePrefix('files');
        $community                  = Utils::setTablePrefix('communities');




        $objUserData->table = 'invitation AS I';
        $objUserData->key = 'invitation_id';
        $objUserData->fields = 'I.*,U.*,C.*,F.*';
        $objUserData->join = "INNER JOIN $users U ON U.user_id = I.invitation_sender_id LEFT JOIN $community C ON C.community_id = I.invitation_entity_id LEFT JOIN $files F ON C.community_image_id = F.file_id";
        $objUserData->where = " I.invitation_receiver_id ='" . $db->escapeString($user_id) . "' 
                                    	AND I.invitation_status='P'";




        $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);
        //echopre($users);
        //return $leads->records;
        return $users;
    }

    public static function getAllMessages($orderfield = '', $orderby = '', $pagenum = 1, $itemperpage = 10) {

        $user_id = Utils::getAuth('user_id');
        $objUserData = new stdClass();
        $db = new Db();
        $users = Utils::setTablePrefix('users');
        $files = Utils::setTablePrefix('files');
        $where                          = '  user_id =' . $db->escapeString($db->escapeString($user_id));
       // $msgcount                 = $db->selectRow($tableName, 'user_message_count', $where);
        $msgcount = 0;
        $db->update($users, array('user_message_count' => $msgcount), $where, $doAudit = false);
        $objUserData->table = 'messages AS messages';
        $objUserData->key = 'message_id';
        $objUserData->fields = 'messages.*,users.*,f.file_path';
        $objUserData->join = "LEFT JOIN  $users AS users ON users.user_id = messages.message_from_id LEFT JOIN $files AS f ON f.file_id = users.user_image_id ";
        $objUserData->where = " message_to_id ='" . $db->escapeString($user_id) . "' AND message_sent_status = 1";

        $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);
        
        //echopre($users);
        //return $leads->records;
        return $users;
    }

    public static function getAllMessagescount($orderfield = '', $orderby = '', $pagenum = 1, $itemperpage = '') {

        $user_id = Utils::getAuth('user_id');
        $objUserData = new stdClass();
        $db = new Db();
        $users = Utils::setTablePrefix('users');
        $objUserData->table = 'messages AS messages';
        $objUserData->key = 'message_id';
        $objUserData->fields = 'messages.*,users.*';
        $objUserData->join = "LEFT JOIN  $users AS users ON users.user_id = messages.message_from_id ";
        $objUserData->where = " message_to_id ='" . $db->escapeString($user_id) . "'";

        $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);
        //echopre($users);
        //return $leads->records;
        return $users;
    }

    public static function getAllBizcomPendingRequest($orderfield = 'invitation_created_on', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10) {

        $user_id = Utils::getAuth('user_id');
        $db = new Db();
        $objUserData = new stdClass();
        $users = Utils::setTablePrefix('users');
        $invite = Utils::setTablePrefix('invitation');
        $community = Utils::setTablePrefix('communities');

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

        $objUserData->table = 'invitation AS I';
        $objUserData->key = 'invitation_id';
        $objUserData->fields = 'I.invitation_id,U.*,F.*,C.*';
        $objUserData->join = "INNER JOIN $community C ON C.community_id = I.invitation_entity_id 
                    INNER JOIN  $users U ON U.user_id = I.invitation_sender_id
                    LEFT JOIN $files F ON C.community_image_id = F.file_id";
        $objUserData->where = " invitation_receiver_id ='" . $db->escapeString($user_id) . "' 
                                    	AND  invitation_entity='C' AND invitation_status='P'";
        //   echo $objUserData->where;

        /* 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);
        //echopre($users);
        //return $leads->records;
        return $users;
    }


    

    public static function getInvitationReport($orderfield = 'invitation_id', $orderby = 'ASC', $pagenum = 1, $itemperpage = 10, $search = '', $searchFieldArray, $userId = '', $search_type = '', $filterstatus = '', $filtertype = '') {

        $db = new Db();

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

        if ($userId > 0) {
            $userWhere = " b.invitation_sender_id = '" . $userId . "'";
        } else {
            $userWhere = "";
        }




        $objLeadData = new stdClass();
        $objLeadData->table = 'invitation AS b';
        $objLeadData->key = 'b.invitation_id';
        $objLeadData->fields = 'b.*,u.*';
        $objLeadData->join = "LEFT JOIN $users as u ON b.invitation_receiver_id = 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) {
                    if ($search_type != 'email') {
                        $objLeadData->where .= " OR concat(user_firstname , ' ' , user_lastname) LIKE '%$search%')";
                    } else {
                        $objLeadData->where .= ")";
                    }
                } else {
                    $objLeadData->where .= " OR";
                }
                $i++;
            }
        }
        if ($filterstatus != '') {
            $objLeadData->where .= "AND invitation_status = '$filterstatus' ";
        }
        if ($filtertype != '') {
            if ($filtertype == 'C') {
                $objLeadData->where .= "AND invitation_entity = '$filtertype' ";
            } else {
                $objLeadData->where .= "AND invitation_entity = 'U' AND invitation_type = '$filtertype' ";
            }
        }
        $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 checkInvitationSentEmail($senderId, $receiverEmail, $entity, $entityId) {
        $db             = new Db();
        $invitation     = Utils::setTablePrefix('invitation');
        $userWhere      = "invitation_type='E'";
        $select         = "count(invitation_id) cnt";
        $userWhere1     = " AND invitation_sender_id=$senderId";
        $userWhere2     = " AND invitation_receiver_email='$receiverEmail'";
        $userWhere3     = " AND invitation_entity='$entity'";
        $userWhere4     = " AND invitation_entity_id=$entityId";
        $where          = $userWhere . $userWhere1 . $userWhere2 . $userWhere3 . $userWhere4;
        $query          = "SELECT $select FROM $invitation WHERE $where";
        $result         = $db->checkExists('invitation', 'invitation_id', $where);
        return $result;
    }

    public static function sendmessage($to_user_id) {
        $db = new Db();
        $objSession = new LibSession();
        $tableName              = 'users';
        $tableName1              = Utils::setTablePrefix('users');
        $from_user_id = $objSession->get('user_id', 'default');
        $message_details = $_POST['message_detail'];
        $message_subject = $_POST['message_subject'];
        //$messages = Utils::setTablePrefix('messages');
        $data['message_detail'] = $message_details;
        $data['message_to_id'] = $to_user_id;
        $data['message_from_id'] = $from_user_id;
        $data['message_date'] = date('Y-m-d', time());
        $data['message_subject'] = $message_subject;
        $result = $db->addFields('messages', $data);
        $where                          = '  user_id =' . $db->escapeString($to_user_id);
        $msgcount                 = $db->selectRow($tableName, 'user_message_count', $where);
       // echopre1($msgcount);exit;
        $msgcount++;
        $db->update($tableName1, array('user_message_count' => $msgcount), $where, $doAudit = false);
//     	echopre($result);
        return $result;
    }

    public static function deletemessage($message_id) {
        $db                     = new Db();
        $user_id                = Utils::getAuth('user_id');
        $messages               = Utils::setTablePrefix('messages');
        $query = "UPDATE $messages SET message_sent_status = '0' WHERE message_id = $message_id AND message_to_id = $user_id";
        $result = $db->customQuery($query);
//    	echopre($result);
        return $result;
    }

    public static function showmessage($message_id) {
        $db                     = new Db();
        $messages               = Utils::setTablePrefix('messages');
        $query = "SELECT * FROM $messages WHERE message_id = $message_id";
        $result = $db->selectQuery($query);
//    	echopre($result);
        return $result;
    }

    //Get Introduction details
    public static function getIntroductionDetails($invitationId) {
        $objResult                  = new Messages();
        $objResult->status          = SUCCESS;
        //Select User Record If User id is not null
        if ($invitationId != '') {
            $db                     = new Db();
            $tableName              = 'initiate_introductions';
            $tableName1              = Utils::setTablePrefix('pif');
            $selectCase             = '  introduction_id =' . $db->escapeString($invitationId) . ' ';
            Logger::info($selectCase);
            $objResultRow           = $db->selectRecord($tableName, '*', $selectCase);
            // 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 = GROUP_ID_NOT_EXIST; // User not exists
            }
          $query = "select count(*) as count from $tableName1 where introduction_id ='". $db->escapeString($invitationId)."'";
             $objResultRow1           = $db->selectQuery($query);
            // echopre($objResultRow1);
              $objResult->count = $objResultRow1[0]->count; 
        }
        Logger::info($objResult);
        return $objResult;
    }

    //Change introduction status
    public static function changeIntroductionStatus($invitationId = '', $objConnectionsVo = '') {
        $objResult                  = new Messages();
        $objResult->status          = SUCCESS;
        $data = array();
        if ($invitationId == '') {
            $objResult->status      = "ERROR";
            $objResult->message     = GROUP_ID_NOT_EXIST; // Email Alreday Exists
        }
        if ($objResult->status == SUCCESS) {
            $db                     = new Db();
            $tableName              = Utils::setTablePrefix('initiate_introductions');
            $where                  = "introduction_id = " . $db->escapeString($invitationId) . " ";
            $data                   = Utils::objectToArray($objConnectionsVo);
            $customerId             = $db->update($tableName, $data, $where, $doAudit = false);
            $objConnectionsVo->introduction_id = $invitationId;
            $objResult->data        = $objConnectionsVo;
        }
        Logger::info($objResult);
        return $objResult;
    }
    
    
    public static function setUserAcceptJoineeApprovalStatus($campign_id,$communityId,$pifstatus,$voucher_no,$exp_date,$termsncondition,$amount,$bbfnumber,$joinee_id,$joinee_voucher_no,$joinee_exp_date,$joinee_termsncondition,$joinee_amount,$joinee_bbfnumber){
        $db                                         = new Db();
        $objSession                                 = new LibSession();
        
        $member                                     = Utils::setTablePrefix('community_member');
        $pif                                        = Utils::setTablePrefix('pif');
        $query                                      = "SELECT cmember_pif_id 
                                                        FROM $member  
                                                        WHERE cmember_id =$joinee_id  
                                                        AND cmember_community_id=$communityId";
                Logger::info($query);
                $objResultRow                       = $db->fetchSingleRow($query);
                $pif_id                        = $objResultRow->cmember_pif_id;
                $query                                      = "SELECT * 
                                                        FROM $pif  
                                                        WHERE pif_id =$pif_id";
                Logger::info($query);
                $pifDetails                       = $db->fetchSingleRow($query);
                $pif_user_id                        = $pifDetails->pif_from_user_id;
        $from_user_id                               = $objSession->get('user_id', 'default');
        $campaignDetails                            = self::getCampaignDetailsFromCampaignId($campign_id);
        //echopre($campaignDetails);
            if($campaignDetails->data->refferalcampaign_paidrefferalmode==3 && $pifstatus=='A'){
                //---------Insert Voucher details--------------------------
                 $tableName     = Utils::setTablePrefix('voucher_details');
                 $data_array    = array(
                                    "campaign_id"                   => $campign_id,
                                    "bizcom_id"                     => $campaignDetails->data->refferalcampaign_bizcom_id,
                                    "from_user_id"                  => $from_user_id,
                                    "to_user_id"                    => $pif_user_id,
                                    "bbf_number"                    => $bbfnumber,
                                    "voucher_number"                => $voucher_no,
                                    "voucher_expiry_date"           => date('Y-m-d',strtotime($exp_date)),
                                    "voucher_terms_n_conditions"    => $termsncondition,
                                    "voucher_amount"                => $amount
                                );
                 $joinee_data_array    = array(
                                    "campaign_id"                   => $campign_id,
                                    "bizcom_id"                     => $campaignDetails->data->refferalcampaign_bizcom_id,
                                    "from_user_id"                  => $from_user_id,
                                    "to_user_id"                    => $joinee_id,
                                    "bbf_number"                    => $joinee_bbfnumber,
                                    "voucher_number"                => $joinee_voucher_no,
                                    "voucher_expiry_date"           => date('Y-m-d',strtotime($joinee_exp_date)),
                                    "voucher_terms_n_conditions"    => $joinee_termsncondition,
                                    "voucher_amount"                => $joinee_amount
                                );
                $communityId = $db->insert($tableName, $data_array);
                $communityId = $db->insert($tableName, $joinee_data_array);
                //------Send Voucher --------------------------------------
                
                //------username and user email
                $userdetails                            = User::getUserDetail($pif_user_id);
                //echopre($userdetails);
                $mailIds                                = array();
		$replaceparams                          = array();
		$mailIds[$userdetails->data->Email]     = '';
		$replaceparams['NAME']                  = $userdetails->data->Name;
		$replaceparams['VOUCHER_NUMBER']        = $voucher_no;
		$replaceparams['AMOUNT']                = $amount;
		$replaceparams['EXPIRY']                = $exp_date;
                $replaceparams['TERMSNCONDITION']       = $termsncondition;
                $replaceparams['BBFNUMBER']             = $bbfnumber;
		$objMailer                              = new Mailer();
		$objMailer->sendMail($mailIds, 'PIF_VOUCHER_MAIL', $replaceparams);
                
                //------Joinee username and user email
                $joineedetails                          = User::getUserDetail($joinee_id);
                $mailIds                                = array();
		$replaceparams                          = array();
		$mailIds[$joineedetails->data->Email]     = '';
		$replaceparams['NAME']                  = $joineedetails->data->Name;
		$replaceparams['VOUCHER_NUMBER']        = $joinee_voucher_no;
		$replaceparams['AMOUNT']                = $joinee_amount;
		$replaceparams['EXPIRY']                = $joinee_exp_date;
                $replaceparams['TERMSNCONDITION']       = $joinee_termsncondition;
                $replaceparams['BBFNUMBER']             = $joinee_bbfnumber;
		$objMailer                              = new Mailer();
		$objMailer->sendMail($mailIds, 'PIF_VOUCHER_MAIL', $replaceparams);
            }
            
        
       
    
    }
    
    public static function setJoineeAccountAmount($campign_id,$user_id){
        $db                         = new Db();
        $account                    = Utils::setTablePrefix('refferal_account');
        $campiagnDetails            = self::getCampaignDetailsFromCampaignId($campign_id);
        //echopre1($campiagnDetails);
        if($campiagnDetails->data->refferalcampaign_payment_mode    == 'P'){
             $query                  =   " SELECT account_id,account_total_joinees FROM $account 
                                            WHERE account_campaign_id=$campign_id 
                                            AND account_user_id=$user_id";
            Logger::info($query);
                $objResultRow       = $db->fetchSingleRow($query);
                if($objResultRow->account_id >0){
                    $numjoinees   = $objResultRow->account_total_joinees+1;
                    $joineeincetive = $campiagnDetails->data->refferalcampaign_max_joins*$numjoinees;
                     $dataArray   = array(
                                    'account_total_joinees'             =>$numjoinees ,
                                    'account_total_joinee_incentive'    => $joineeincetive
                   );
                   if($campiagnDetails->data->refferalcampaign_paidrefferalmode==3){
                     $dataArray['account_new_joinees_incentive']=  $campiagnDetails->data->referralcampaign_new_joinee_incentive*$numjoinees; 
                   }
                   $where                                       ='account_user_id='.$user_id.' AND account_campaign_id='.$campign_id;
                   $cId                                         = $db->update($account, $dataArray, $where, $doAudit = false); 
                }
                else{
                   $dataArray   =array(
                                    'account_user_id'               => $user_id,
                                    'account_campaign_id'           => $campign_id,
                                    'account_total_pif_sent'        => 1,
                                    'account_total_pif_incentive'   => $campiagnDetails->data->refferalcampaign_max_joins
                   );
                   if($campiagnDetails->data->refferalcampaign_paidrefferalmode==3){
                     $dataArray['account_new_joinees_incentive']=  $campiagnDetails->data->referralcampaign_new_joinee_incentive*$numjoinees; 
                   }
                   $cId                                         = $db->insert($account, $dataArray); 
                }
                
            }
        }
        //Change charity organisation
    public static function changeCharitySelection($dataaray,$invitationId) {
        $objResult                  = new Messages();
        $objResult->status          = SUCCESS;
        $data                       = array();
        if ($objResult->status == SUCCESS) {
            $db                     = new Db();
            $tableName              = Utils::setTablePrefix('initiate_introductions');
            $where                  = "introduction_id = " . $db->escapeString($invitationId) . " ";
            $customerId             = $db->update($tableName, $dataaray, $where, $doAudit = false);
            $objConnectionsVo->introduction_id = $invitationId;
            $objResult->data        = $objConnectionsVo;
        }
        Logger::info($objResult);
        return $objResult;
    }
    
    public static function getAllSentMessages($orderfield = '', $orderby = '', $pagenum = 1, $itemperpage = 10) {

        $user_id = Utils::getAuth('user_id');
        $objUserData = new stdClass();
        $db = new Db();
        $users = Utils::setTablePrefix('users');
        $objUserData->table = 'messages AS messages';
        $objUserData->key = 'message_id';
        $objUserData->fields = 'messages.*,users.*';
        $objUserData->join = "LEFT JOIN  $users AS users ON users.user_id = messages.message_to_id ";
        $objUserData->where = " message_from_id ='" . $db->escapeString($user_id) . "' AND message_status = 1";

        $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);
        //echopre($users);
        //return $leads->records;
        return $users;
    }
    
    public static function getTerms() {
            $db                     = new Db();
            $tableName              = Utils::setTablePrefix('content');
             $query                                     = "SELECT content_description 
                                                        FROM $tableName  
                                                        WHERE content_alias = 'specialterms'";
                Logger::info($query);
                $objResultRow                       = $db->fetchSingleRow($query);
        return $objResultRow;
    }
    public static function getTermsPif() {
            $db                     = new Db();
            $tableName              = Utils::setTablePrefix('content');
             $query                                     = "SELECT content_description 
                                                        FROM $tableName  
                                                        WHERE content_alias = 'pifterms'";
                Logger::info($query);
                $objResultRow                       = $db->fetchSingleRow($query);
        return $objResultRow;
    }
    public static function sendMessages($message_detail,$message_to_id,$message_from_id,$message_date,$message_subject) {
        $db = new Db();
        $data = array();
        $tableName              = Utils::setTablePrefix('users');
                $data['message_detail'] = $message_detail;
                $data['message_to_id'] = $message_to_id;
                $data['message_from_id'] = $message_from_id;
                $data['message_date'] = $message_date;
                $data['message_subject'] = $message_subject;
               // echopre1($data);
               // $result = $db->addFields('messages', $data);
        $result = $db->addFields('messages', $data);
        $where                          = '  user_id =' . $db->escapeString($message_to_id);
        $msgcount                 = $db->selectRow('users', 'user_message_count', $where);
        $msgcount++;
        $db->update($tableName, array('user_message_count' => $msgcount), $where, $doAudit = false);
//     	echopre($result);
        return $result;
    }
     public static function deletesentmessage($message_id) {
        $db                    = new Db();
        $user_id               = Utils::getAuth('user_id');
        $messages              = Utils::setTablePrefix('messages');
        $query = "UPDATE $messages SET message_status = '0' WHERE message_id = $message_id AND message_from_id = $user_id";
        $result = $db->customQuery($query);
//    	echopre($result);
        return $result;
    }
    
    public static function getAllNewMessages() {
        $db             = new Db();
        $user_id               = Utils::getAuth('user_id');
        $messages     = Utils::setTablePrefix('messages');
        $users     = Utils::setTablePrefix('users');
        $userWhere      = "M.message_to_id= $user_id AND M.message_read_status= '0'";
        $select         = "*";
        $query          = "SELECT M.*,U.user_alias,U.user_image_name,CONCAT(U.user_firstname,' ',U.user_lastname)AS user FROM $messages AS M LEFT JOIN $users AS U ON M.message_from_id = U.user_id WHERE $userWhere";
       // echo $query;
        $objResultRow = $db->fetchAll($db->execute($query));
      //  echopre1($objResultRow);
        return $objResultRow;
    }
    }

?>
