<?php

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

class chat_model extends CI_Model
{

    function __construct()
    {
        parent::__construct();
    }
    public function add_user($data){
        $this->db->insert('chat_users',$data);
		return $this->db->insert_id();
    }
	public function check_duplicate($email){
       $query= $this->db->select(['*'])->from('chat_users')->where('email',$email)->get();
        return $query->num_rows();
    }
	public function check_email_exist($email){
       $query= $this->db->select(['*'])->from('chat_users')->where('email',$email)->get();
        return $query->row();
    }
    public function get_all_online($status){
       $query= $this->db->select(['*'])->from('chat_users')->where('status',$status)->get();
        return $query->result();
    }
    public function get_by_id($id){
        $this->db->where('id',$id);
        return $this->db->get('chat_users')->row();
    }
    public function update($id,$data){
        $this->db->where('id', $id);
        $this->db->update('chat_users', $data);
    }
    public function login(){
        $query = $this->db->get_where('chat_users', 
            array(
            'email' => $this->input->post('email'),
        ));

        $row = $query->result();
        $num_rows = $query->num_rows();

        if( $num_rows == 1 && password_verify($this->input->post('password'), $row[0]->password) ){


            $newdata = array(
              'id'        => $row[0]->id,
              'user_name' => $row[0]->username,
              'email'     => $row[0]->email, 
            );

            $this->session->set_userdata($newdata);
                
            
            return $num_rows;
        }
    }
	public function insert_message($data){
		$this->db->insert('chat_user_message_history',$data);
		return $this->db->insert_id();
	}
	public function fetch_message($userid){
		$query2 =$this->db->select(['*'])->from('chat_users')->where('id',$userid)->get();
		$d = $query2->row();
		//echo $this->db->last_query();
		$query =$this->db->select(['*'])->from('chat_user_message_history')
		->where('date(dated)=current_date()')->where_in('userid',array($userid,$d->chatting_with))
		->get();
		//echo $this->db->last_query();die;
		return $query->result_array();
	}
}
