<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends CI_Model
{
   
    function searchUsers($searchTerm, $myId=null)
    {
        $this->db->select('*');
        $this->db->from('users');
        if($myId)
        $this->db->where('id !=', $myId);
        $this->db->like('name', $searchTerm);
        $this->db->or_like('email', $searchTerm);
        $this->db->order_by('name', 'asc');
        $query = $this->db->get();
        
        $result = $query->result_array();
        return $result;
    }

    function getMyOrders($myId) {
        $this->db->select('BaseTbl.*, products.title');
        $this->db->from('orders as BaseTbl');
        $this->db->join('products','products.id = BaseTbl.productId', 'left');
        
        $this->db->where("BaseTbl.userId = $myId");
        
        $this->db->order_by('BaseTbl.orderDate', 'asc');
        $query = $this->db->get();
        
        $result = $query->result();
        return $result;
    }

    function getMessages($myId, $otherUserId=null, $lastMessageDateTime=null) {
        $this->db->select('BaseTbl.*, user1.name as sender, user1.image as senderImage, user2.name as receiver, user1.image as receiverImage');
        $this->db->from('chats as BaseTbl');
        $this->db->join('users as user1','user1.id = BaseTbl.fromId', 'left');
        $this->db->join('users as user2','user2.id = BaseTbl.toId', 'left');
        
        $this->db->where("(BaseTbl.fromId = $myId OR BaseTbl.toId = $myId)");
        if($otherUserId){
            $this->db->where("(BaseTbl.fromId = $otherUserId OR BaseTbl.toId = $otherUserId)");
            
            // if(is_array($otherUserId)){

            //     $this->db->where_in("BaseTbl.fromId = $otherUserId");
            // }else{
            //     $this->db->where("(BaseTbl.fromId = $otherUserId OR BaseTbl.toId = $otherUserId)");

            // }
        }
        if($lastMessageDateTime){
            $this->db->where("BaseTbl.createdDate >", $lastMessageDateTime);
        }
        $this->db->order_by('BaseTbl.createdDate', 'asc');
        $query = $this->db->get();
        
        $result = $query->result();
        return $result;
    }

    function getQuestions() {
        $this->db->select('*');
        $this->db->from('quaiz');
        $query = $this->db->get();
        
        $result = $query->result_array();
        return $result;
    }

    function getLastMessage($myId, $otherUserId) {
        $this->db->select('*');
        $this->db->from('chats');
        
        $this->db->where("(fromId = $myId AND toId = $otherUserId) OR (fromId = $otherUserId AND toId = $myId)");
        
        $this->db->order_by('createdDate', 'desc');
        $query = $this->db->get();
        
        $result = $query->result();
        
        if(count($result) > 0){

            return $result[0]->message;
        }else{
            return 'no message';
        }
    }

    function saveMyChat($myChatData)
    {
        $this->db->trans_start();
        $this->db->insert('mychats', $myChatData);
        
        $this->db->trans_complete();
        
        return true;
    }

    function removeMyChat($myId, $otherId)
    {
        $this->db->trans_start();
        
      //  $this->db->where('myId', $myId);
        $this->db->where('id', $otherId);
        $this->db->delete('mychats');

        $this->db->where('conversationId', $otherId);
        //$this->db->where('toId', $otherId);
        $this->db->delete('chats');

        //$this->db->where('toId', $myId);
        //$this->db->where('fromId', $otherId);
        //$this->db->delete('chats');
        
        $this->db->trans_complete();
        
        return true;
    }

    function saveMessage($messageData)
    {
        $this->db->trans_start();
        $this->db->insert('chats', $messageData);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return true;
    }

    function saveQuestions($userInfo)
    {
        $this->db->trans_start();
        $this->db->insert('questions', $userInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return true;
    }

    function addNewUser($userInfo)
    {
        $this->db->trans_start();
        $this->db->insert('users', $userInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return $insert_id;
    }
    
    function getUserRoles()
    {
        $this->db->select('roleId, role, status as roleStatus');
        $this->db->from('tbl_roles');
        $query = $this->db->get();
        
        return $query->result();
    }

    function checkEmailExists($email, $userId = 0)
    {
        $this->db->select("email");
        $this->db->from("users");
        $this->db->where("email", $email);   
        if($userId != 0){
            $this->db->where("id !=", $userId);
        }
        $query = $this->db->get();

        return $query->result();
    }
    
    function getUserInfo($userId, $userRole = 'user')
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('id', $userId);
        $this->db->where('role', $userRole);
        $query = $this->db->get();
        
        return $query->row();
    }

    function getUserSubscriptions($userId)
    {
        $this->db->select('*');
        $this->db->from('subscriptions');
        $this->db->where('userId', $userId);
        $this->db->where('status', 'active');
        $query = $this->db->get();
        
        return $query->row();
    }

    function addSubscription($subscriptionInfo)
    {
        $this->db->trans_start();
        $this->db->insert('subscriptions', $subscriptionInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return $insert_id;
    }

    function isUserSubscribed($userId)
    {
        $this->db->select('*');
        $this->db->from('subscriptions');
        $this->db->where('userId', $userId);
        $this->db->where('status', 'active');
        $query = $this->db->get();
        $numrows = $query->num_rows();

        if($numrows > 0){
            // $row = $query->row();
            // $startDate = $row->startDate;
            // echo($startDate);
            // $startDate = date('Y-m-d h:i:s', strtotime('+1 month', strtotime($startDate)));
            // $startDate = strtotime($startDate);
            // $todayDate = date('Y-m-d h:i:s');
            // echo('<br>');
            // echo($todayDate);
            // $todayDate = strtotime($todayDate);
            // echo('<br>');
            // echo($startDate);
            // echo('<br>');
            // echo($todayDate);
            // die;
            // if($todayDate > $startDate){
            //     $subscriptionInfo = ['status' => 'expired'];
            //     $this->db->where('userId', $userId);
            //     $this->db->update('subscriptions', $subscriptionInfo);
            //     return false;
            // }
            return true;
        }else{
            
            return false;
        }
        
    }

    function getUserQuestions($userId, $userRole = 'user')
    {
        $this->db->select('*');
        $this->db->from('questions');
        $this->db->where('userId', $userId);
        $query = $this->db->get();
        
        return $query->row();
    }

    function getProducts()
    {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->where('isDeleted', 0);
        $query = $this->db->get();
        
        return $query->result();
    }
    
        function searchProducts($searchTerm)
    {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->where('isDeleted', 0);
        $this->db->group_start();
        $this->db->like('title', $searchTerm);
        $this->db->or_like('description', $searchTerm);
        $this->db->or_like('storeAddress', $searchTerm);
        $this->db->group_end();
        $query = $this->db->get();

        return $query->result();
    }

    function getProductById($productId)
    {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->where('id', $productId);
        $this->db->where('isDeleted', 0);
        $query = $this->db->get();
        
        return $query->row();
    }

    function addOrder($orderInfo)
    {
        $this->db->trans_start();
        $this->db->insert('orders', $orderInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return $insert_id;
    }

    function getOnlineUsers($userId, $userRole = 'user')
    {
        $this->db->select('BaseTbl.*');
        $this->db->from('users as BaseTbl');
        $this->db->join('mychats','mychats.otherId = BaseTbl.id', 'left');
        $this->db->where('BaseTbl.id !=', $userId);
        $this->db->where("mychats.myId = '$userId' OR mychats.otherId = '$userId'");
        // $this->db->where('mychats.myId', $userId);
        $this->db->where('BaseTbl.role', $userRole);
        // $this->db->where('isOnline', 1);
        $query = $this->db->get();
        
        return $query->result_array();
    }

    
    function getAllUsers($userId, $userRole = 'user')
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('id !=', $userId);
        $this->db->where('role', $userRole);
        $query = $this->db->get();
        
        return $query->result_array();
    }

    function editQuestions($userInfo, $userId)
    {
        $this->db->where('userId', $userId);
        $this->db->update('questions', $userInfo);
        
        return TRUE;
    }
    
    function editUser($userInfo, $userId)
    {
        $this->db->where('id', $userId);
        $this->db->update('users', $userInfo);
        
        return TRUE;
    }
    
    function deleteUser($userId)
    {
        $this->db->where('id', $userId);
        $this->db->delete('users');
        
        return $this->db->affected_rows();
    }

    function matchOldPassword($userId, $oldPassword)
    {
        $this->db->select('userId, password');
        $this->db->where('userId', $userId);        
        $this->db->where('isDeleted', 0);
        $query = $this->db->get('tbl_users');
        
        $user = $query->result();

        if(!empty($user)){
            if(verifyHashedPassword($oldPassword, $user[0]->password)){
                return $user;
            } else {
                return array();
            }
        } else {
            return array();
        }
    }
   
    function changePassword($userId, $userInfo)
    {
        $this->db->where('userId', $userId);
        $this->db->where('isDeleted', 0);
        $this->db->update('tbl_users', $userInfo);
        
        return $this->db->affected_rows();
    }


    function getUserInfoById($userId)
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('id', $userId);
        $query = $this->db->get();
        
        return $query->row();
    }

    function getUserInfoByIdArray($userId)
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('id', $userId);
        $query = $this->db->get();
        
        return $query->row_array();
    }

    function getUserInfoByEmail($email)
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('email', $email);
        $query = $this->db->get();
        
        return $query->row();
    }

    function getUserInfoWithRole($userId)
    {
        $this->db->select('BaseTbl.userId, BaseTbl.email, BaseTbl.name, BaseTbl.mobile, BaseTbl.isAdmin, BaseTbl.roleId, Roles.role');
        $this->db->from('tbl_users as BaseTbl');
        $this->db->join('tbl_roles as Roles','Roles.roleId = BaseTbl.roleId');
        $this->db->where('BaseTbl.userId', $userId);
        $this->db->where('BaseTbl.isDeleted', 0);
        $query = $this->db->get();
        
        return $query->row();
    }

    function Is_already_register($id)
        {
            $this->db->where('login_oauth_uid', $id);
            $query = $this->db->get('users');
        if($query->num_rows() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    function hasAnswers($id)
        {
        $this->db->where('userId', $id);
        $query = $this->db->get('questions');
        if($query->num_rows() > 0)
        {
            return true;
        }
        else
        {
            return true;
        }
    }

    function Update_user_data($data, $id)
    {
        $this->db->where('login_oauth_uid', $id);
        $this->db->update('users', $data);
    }

    function Insert_user_data($data)
    {
        $this->db->insert('users', $data);
        $insert_id = $this->db->insert_id();
        return $insert_id;
    }

    function getUserInfoByUid($login_oauth_uid)
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('login_oauth_uid', $login_oauth_uid);
        $query = $this->db->get();
        
        return $query->row();
    }

    public function isEmailExists($email)
    {
        $this->db->where('email', $email);
        $query = $this->db->get('users');

        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Get users listing with pagination and search
     */
    function users($searchText = '', $page = 0, $segment = 10)
    {
        $this->db->select('BaseTbl.*');
        $this->db->from('users as BaseTbl');
        $this->db->where('BaseTbl.role', 'user');
        if(!empty($searchText)) {
            $likeCriteria = "(BaseTbl.name LIKE '%".$searchText."%'
                            OR BaseTbl.email LIKE '%".$searchText."%'
                            OR BaseTbl.phone LIKE '%".$searchText."%')";
            $this->db->where($likeCriteria);
        }
        $this->db->order_by('BaseTbl.id', 'DESC');
        $this->db->limit($segment, $page);
        $query = $this->db->get();
        
        $result = $query->result();        
        return $result;
    }

    /**
     * Get users count
     */
    function userCount($searchText = '')
    {
        $this->db->select('BaseTbl.id');
        $this->db->from('users as BaseTbl');
        $this->db->where('BaseTbl.role', 'user');
        if(!empty($searchText)) {
            $likeCriteria = "(BaseTbl.name LIKE '%".$searchText."%'
                            OR BaseTbl.email LIKE '%".$searchText."%'
                            OR BaseTbl.phone LIKE '%".$searchText."%')";
            $this->db->where($likeCriteria);
        }
        $query = $this->db->get();
        
        return $query->num_rows();
    }

    /**
     * Get all agents
     */
    function allAgents()
    {
        $this->db->select('id, name, email');
        $this->db->from('users');
        $this->db->where('role', 'agent');
        $query = $this->db->get();
        
        return $query->result();
    }

    /**
     * Get managers listing
     */
    function managers($searchText = '', $page = 0, $segment = 10)
    {
        $this->db->select('BaseTbl.*');
        $this->db->from('users as BaseTbl');
        $this->db->where('BaseTbl.role', 'manager');
        if(!empty($searchText)) {
            $likeCriteria = "(BaseTbl.name LIKE '%".$searchText."%'
                            OR BaseTbl.email LIKE '%".$searchText."%'
                            OR BaseTbl.phone LIKE '%".$searchText."%')";
            $this->db->where($likeCriteria);
        }
        $this->db->order_by('BaseTbl.id', 'DESC');
        $this->db->limit($segment, $page);
        $query = $this->db->get();
        
        $result = $query->result();        
        return $result;
    }

    /**
     * Get managers count
     */
    function managerCount($searchText = '')
    {
        $this->db->select('BaseTbl.id');
        $this->db->from('users as BaseTbl');
        $this->db->where('BaseTbl.role', 'manager');
        if(!empty($searchText)) {
            $likeCriteria = "(BaseTbl.name LIKE '%".$searchText."%'
                            OR BaseTbl.email LIKE '%".$searchText."%'
                            OR BaseTbl.phone LIKE '%".$searchText."%')";
            $this->db->where($likeCriteria);
        }
        $query = $this->db->get();
        
        return $query->num_rows();
    }

    /**
     * Get all managers
     */
    function allManagers()
    {
        $this->db->select('id, name, email');
        $this->db->from('users');
        $this->db->where('role', 'manager');
        $query = $this->db->get();
        
        return $query->result();
    }

    /**
     * Get agents listing
     */
    function agents($searchText = '', $page = 0, $segment = 10)
    {
        $this->db->select('BaseTbl.*');
        $this->db->from('users as BaseTbl');
        $this->db->where('BaseTbl.role', 'agent');
        if(!empty($searchText)) {
            $likeCriteria = "(BaseTbl.name LIKE '%".$searchText."%'
                            OR BaseTbl.email LIKE '%".$searchText."%'
                            OR BaseTbl.phone LIKE '%".$searchText."%')";
            $this->db->where($likeCriteria);
        }
        $this->db->order_by('BaseTbl.id', 'DESC');
        $this->db->limit($segment, $page);
        $query = $this->db->get();
        
        $result = $query->result();        
        return $result;
    }

    /**
     * Add new manager
     */
    function addNewManager($userInfo)
    {
        $this->db->trans_start();
        $this->db->insert('users', $userInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return $insert_id;
    }

    /**
     * Add new agent
     */
    function addNewAgent($userInfo)
    {
        $this->db->trans_start();
        $this->db->insert('users', $userInfo);
        
        $insert_id = $this->db->insert_id();
        
        $this->db->trans_complete();
        
        return $insert_id;
    }

}