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

// include FCPATH . '/vendor/autoload.php';
// require __DIR__ . '/../vendor/autoload.php';
require 'vendor/autoload.php';



use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
use ElephantIO\Exception\ServerConnectionFailureException;

class Common_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /*
        @Description  : get all data from table
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_all($table, $order_by = '' , $order = '' ,$return_type = 'object')
	{
		$this->db->select('*');

		$this->db->from($table);

		if($order_by != '' && $order != '')
		{
			$this->db->order_by($order_by, $order);
		}

		$query = $this->db->get();

		if($return_type == 'object')
		{
			return $query->result();
		}
		else
		{
			return $query->result_array();
		}
	}

	/*
        @Description  : get single row from table by key
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_single_result($table,  $where_array , $return_type = 'object')
	{
		$this->db->select('*');

		$this->db->from($table);

		$this->db->where($where_array);

		$this->db->limit(1);

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->result();
		}
		else
		{
			$result = $query->result_array();
		}

		if(count($result) > 0)
		{
			return $result['0'];
		}
		else
		{
			return array();
		}
	}

	function get_selected_data_where_array($fields = '', $table,  $where_array)
	{
		$this->db->select($fields);

		$this->db->from($table);

		$this->db->where($where_array);
		return $query = $this->db->get()->result_array();
	}
	/*
        @Description  : get multiple row from table with multiple where conditions
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_by_where_array($table, $where_array , $return_type = 'object')
	{
		$this->db->select('*');

		$this->db->from($table);

		$this->db->where($where_array);

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->result();
		}
		else
		{
			$result = $query->result_array();
		}

		return $result;
	}

	/*
        @Description  : get multiple row from table with multiple where conditions
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_by_where_master($table, $where_array = array() , $where_in_array = array() , $where_string = '' ,$return_type = 'object')
	{
		$this->db->select('*');

		$this->db->from($table);

		if(count($where_array) > 0)
		{
			$this->db->where($where_array);
		}

		if($where_string != '')
		{
			$this->db->where($where_array);
		}

		if(count($where_in_array) > 0)
		{
			foreach($where_in_array as $where_in_detail)
			{
				if($where_in_detail['type'] == 'in')
				{
					$this->db->where_in($where_in_detail['field'], $where_in_detail['values']);
				}
				else if($where_in_detail['type'] == 'not_in')
				{
					$this->db->where_not_in($where_in_detail['field'], $where_in_detail['values']);
				}
			}
		}

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->result();
		}
		else
		{
			$result = $query->result_array();
		}

		return $result;
	}

	/*
        @Description  : get multiple row from table by key as relations of columns
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_by_where_string($table, $where_string, $return_type = 'object')
	{
		$this->db->select('*');

		$this->db->from($table);

		$this->db->where("(".$where_string.")");

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->result();
		}
		else
		{
			$result = $query->result_array();
		}

		return $result;
	}



	/*
        @Description  : get multiple row from table not in array
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function select_by_where_in_or_not_in($fields, $table, $key, $where_array, $in_or_not_in_type = 'in' , $return_type = 'array')
	{
		$this->db->select($fields);

		$this->db->from($table);

		if($in_or_not_in_type == 'in')
		{
			$this->db->where_in($key, $where_array);
		}
		else
		{
			$this->db->where_not_in($key, $where_array);
		}

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->result();
		}
		else
		{
			$result = $query->result_array();
		}

		return $result;
	}



    /*
        @Description  : Insert all data in table
        @Author       : Naresh Lakhara
        @Input        : Array to insert and table name in second parameter
        @Date         : 26-08-2020
    */
	function insert_data($table, $data)
	{
		$this->db->insert($table, $data);

		$id = $this->db->insert_id();

		if($id)
		{
			return $id;
		}
		else
		{
			return FALSE;
		}
	}

	/*
	@Description	: Function to insert batch data
	@Author			: Naresh Lakhara
	@Date			: 26-08-2020
	*/

	function insert_batch_data($table_name , $batch_data)
	{
		if(is_array($batch_data) && count($batch_data) > 0)
		{
			$this->db->insert_batch($table_name , $batch_data);
			return $this->db->insert_id();
		}
	}


    /*
		@Description  : Update all by multiple keys
		@Author       : Naresh Lakhara
		@Date         : 26-08-2020
    */
    function update_by_where_array($table, $where_array = array() , $data)
    {
   		if(count($where_array) > 0)
		{
			$this->db->where($where_array);
		}

		$res = $this->db->update($table, $data);

		if($res)
		{
			return $res;
		}
		else
		{
			return FALSE;
		}
	}

   /*
		@Description  : Update all by where string
		@Author       : Naresh Lakhara
		@Date         : 26-08-2020
    */
    function update_by_where_string($table, $where_string = '' , $data)
    {
   		if(count($where_string) > 0)
		{
			$this->db->where("(".$where_string.")");
		}

		$res = $this->db->update($table, $data);
		return $res;
	}





    /*
		@Description  : delete all by multiple keys
		@Author       : Naresh Lakhara
		@Date         : 26-08-2020
    */
    function delete_by_where_array($table, $where_array)
    {
		if(count($where_array) > 0)
		{
			$this->db->where($where_array);
		}
		$res = $this->db->delete($table);

		if($res)
		{
			return $res;
		}
		else
		{
			return FALSE;
		}
	}

    /*
		@Description  : delete all by where string
		@Author       : Naresh Lakhara
		@Date         : 26-08-2020
    */
   	function delete_by_where_string($table, $where_string)
   	{
		if(count($where_string) > 0)
		{
			$this->db->where("(".$where_string.")");
		}

		$this->db->delete($table);
	}

	 /*
		@Description  : delete all by where in
		@Author       : Naresh Lakhara
		@Date         : 26-08-2020
	*/
    function delete_by_where_in($table, $where_in_array , $field)
    {
		if(count($where_in_array) > 0)
		{
			$this->db->where_in($field,$where_in_array);
		}

		$this->db->delete($table);
	}


	/*
    @Description: common Model for encrypt Script
    @Author: Naresh Lakhara
    @Input:
    @Output:
    @Date: 26-08-2020*/

	function encrypt_script($string)
	{
		$key = $this->config->item('encryption_key');

		$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

		return $encrypted;
	}

	/*
	@Description: common Model for decrypt Script
	@Author: Naresh Lakhara
	@Input:
	@Output:
	@Date: 26-08-2020
	*/

	function decrypt_script($string)
	{
		$key = $this->config->item('encryption_key');

		$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

		return $decrypted;
	}

	function get_number_of_rows_table($table,$fields,$where_array = array())
    {
        $this->db->select($fields);

        $this->db->from($table);

        if(count($where_array) > 0)
        	$this->db->where($where_array);

        $query = $this->db->get();

        $num_rows = $query->num_rows();

        return $num_rows;
    }

    /*
        @Description: Function for Get Records Lists tables
        @Author     : Naresh Lakhara
        @Date       : 26-08-2020
    */
    public function select($table_name, $getfields = '', $match_values = '', $condition = '', $compare_type = '', $count = '', $num = '', $offset = '', $orderby = '', $sort = '',$where_clause='',$totalrows='',$group_by='',$where_str='') {
        $fields =  $getfields ? implode(',', $getfields) : '';
        $sql = 'SELECT ';

        $sql .= $fields ? $fields : '*';
        $sql .= ' FROM '.$table_name;
        $where = '';

        if ($match_values) {
            $keys = array_keys($match_values);
            $compare_type = $compare_type ? $compare_type : 'like';
            if($condition!='')
                $and_or=$condition;
            else
                $and_or = ($compare_type == 'like') ? ' OR ' : ' AND ';

            $where = 'WHERE ';
            switch ($compare_type)
            {
                case 'like':
                    $where .= $keys[0].' '.$compare_type .'"%'.$match_values[$keys[0]].'%" ';
                    break;

                case '=':
                default:
                    $where .= $keys[0].' '.$compare_type .'"'.$match_values[$keys[0]].'" ';
                    break;
            }
            $match_values = array_slice($match_values, 1);

            foreach($match_values as $key=>$value)
            {
                $where .= $and_or.' '.$key.' ';
                switch ($compare_type)
                {
                    case 'like':
                        $where .= $compare_type .'"%'.$value.'%"';
                        break;

                    case '=':
                    default:
                        $where .= $compare_type .'"'.$value.'"';
                        break;
                }
            }
        }
        if (!empty($where_clause)) {
            $where .= ' AND (';

            foreach($where_clause as $key=>$val)
            {
                $where .= $key." LIKE '%".$val."%' OR ";
            }
            $where = rtrim($where,'OR ');
            $where .= ')';
        }
        if (!empty($where_str))
            $where .= $where_str;

        if (!empty($group_by)) {
            $sql .=' group by '.$group_by;
        }
        $orderby = ($orderby !='')?' order by '.$orderby.' '.$sort.' ':'';
        if ($num == "0")
            $num = "";
        if ($offset == "0")
            $offset = "";
        if ($offset =="" && $num=="")
            $sql .= ' '.$where.$orderby;
        elseif ($offset=="" && $offset== 0)
            $sql .= ' '.$where.$orderby.' '.'limit '.$num;
        else
            $sql .= ' '.$where.$orderby.' '.'limit '.$offset .','.$num;

        $query = ($count) ? 'SELECT count(*) FROM '.$table_name.' '.$where.$orderby : $sql;
        $query = $this->db->query($query);
        //echo $this->db->last_query();
        if(!empty($totalrows))
            return $query->num_rows();
        else
            return $query->result_array();
    }


    /*
        @Description  : get single row
        @Author       : Naresh Lakhara
        @Output       : Listing
        @Date         : 26-08-2020
    */
	function single_record_fetch($field, $table, $where_array , $return_type = 'array')
	{
		$this->db->select($field);

		$this->db->from($table);

		$this->db->where($where_array);

		$query = $this->db->get();

		if($return_type == 'object')
		{
			$result = $query->row();
		}
		else
		{
			$result = $query->row_array();
		}

		if(!empty($result))
		{
			return $result;
		}
		else
		{
			return array();
		}
	}

	/*
		Author : Naresh Lakhara
		Date   : 31-08-2020
		Description : Email Send
	*/

	function email_send($to = '', $subject = '', $message = '' , $attachment = '', $cc = array()) {

		$config = Array(
		  	'protocol' 		=> 'smtp',
		  	'smtp_host' 	=> 'ssl://smtp.googlemail.com',
		  	'smtp_port' 	=> 465,
           	'smtp_timeout' 	=> '30',
		  	'smtp_user' 	=> AUTH_EMAIL, // change it to yours
		 	'smtp_pass' 	=> AUTH_PASSWORD, // change it to yours
		  	'mailtype' 		=> 'html',
		  	'charset' 		=> 'iso-8859-1',
		  	'wordwrap' => TRUE
		);

	    $this->load->library('email', $config);
	    $this->email->clear(TRUE);
	    $this->email->set_mailtype("html");
	    $this->email->set_newline("\r\n");
		$this->email->from(AUTH_EMAIL); // change it to yours
		$this->email->to($to);// change it to yours

		if(!empty($cc) && isset($cc)) {
			$this->email->cc($cc);
		}
		$this->email->subject($subject);
		$this->email->message($message);

		if(!empty($attachment) && isset($attachment)) {
			$this->email->attach($attachment);
		}

		if(!$this->email->send()) {
		    return false;
		} else {
		    return true;
		}
	}

	/*
		Author 		: Naresh Lakhara
		Date   		: 28-04-2022
		Description : Push Notificaton Send For Andriod and Ios
	*/
	function send_push_notification($user_id, $app_type, $data) {

		$app_info 	  = "";
		$push_send_id = "";

		$field_name      = array('user_id','device_token','app_info');
		$where_condition = array('user_id' => $user_id);
		$emp_data        = $this->Common_model->single_record_fetch($field_name,'zo_tbl_user',$where_condition);
		$device_token    = trim(@$emp_data['device_token']);
		$app_info    	 = explode(' ', @$emp_data['app_info'])[0];
		$push_send_id    = @$emp_data['user_id'] ? (string)$emp_data['user_id'] : "0" ;

		if(!empty($app_info) && isset($app_info)) {

			$url 		= FCM_URL;
			$serverKey  = FCM_SERVER_KEY;
		    $decode_data = (array)json_decode($data,true);

			$app_info = strtolower($app_info);

			if($app_info == 'android') {

	    		$arrayToSend  = array('to' => $device_token, 'data' => $decode_data, 'priority'=>'high');

			} else if ($app_info == 'ios') {

	    		$arrayToSend  = array('to' => $device_token, 'notification' => $decode_data, 'data' => $decode_data, 'priority'=>'high');
			}

		    $json = json_encode($arrayToSend);
		    $headers = array();
		    $headers[] = 'Content-Type:application/json';
		    $headers[] = 'Authorization:key='.$serverKey;
		    $ch = curl_init();
		    curl_setopt($ch, CURLOPT_URL, $url);
		    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
		    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
		    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
		    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		    //Send the request
		    $response = curl_exec($ch);

		    /* save notication log */
		    $decode_obj = json_decode($response);

		    // echo '<pre>';print_r($decode_obj); exit;
		    
		    $data_save = array();
		    $data_save = array(
		    	'send_notification_for' => $app_type,
		    	'result' 				=> @$decode_obj->success? $decode_obj->success: 0,
		    	'multicast_id' 			=> @$decode_obj->multicast_id ? $decode_obj->multicast_id : 0,
		    	'message_id' 			=> @$decode_obj->results[0]->message_id ? $decode_obj->results[0]->message_id : 0,
		    	'push_send_id'          => @$push_send_id,
		    );
		    $this->Common_model->insert_data('zo_push_notification_log',$data_save);
		    // if ($response === FALSE) {

		    // 	die('FCM Send Error: ' . curl_error($ch));
		    // }
		    //Close request
		    curl_close($ch);
		}
	}	

	/*
		Author : Naresh lakhara
		Date   : 08-02-2021
		Description : Url check
	*/
	function does_url_exists($url) {
	    $ch = curl_init($url);
	    curl_setopt($ch, CURLOPT_NOBODY, true);
	    curl_exec($ch);
	    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

	    if ($code == 200) {
	        $status = true;
	    } else {
	        $status = false;
	    }
	    curl_close($ch);
	    return $status;
	}

	/*
		Author : Naresh lakhara
		Date   : 20-07-2021
		Description : GMT convert into india timezone
	*/
	public function gmt_indian_timezone($current_time)
	{
		// date_default_timezone_set("Asia/Kolkata");
		$add_date = date('Y-m-d H:i:s',strtotime('+5 hour +30 minutes +1 seconds',strtotime($current_time)));
		return $add_date;
	}

	/*
		Author : Naresh Lakhara
		Date   : 09-09-2021
		Description   : Last Record Fetch of table
	*/
	public function last_record_fetch($table_name, $sort_field, $sort_type) {

		$query = "SELECT * FROM $table_name ORDER BY $sort_field $sort_type";

        $query_exe = $this->db->query($query);

		if($query_exe->num_rows() > 0 ) {

		 	$employee_data =  $query_exe->row_array();

		 	return $employee_data;

		} else {

			return array();
		}
	}

	/*
		Author : Naresh Lakhara
		Date   : 04-02-2022
		Description   : Send FCM
	*/
	public function Send_FCM($video_id, $device_type, $lock_mac, $btn_action)
	{
        require_once APPPATH."third_party/firebase.php";
        require_once APPPATH."third_party/push.php";
	    // error_reporting(-1);
	    // ini_set('display_errors', 'On');
	    $firebase = new Firebase();
	    $push = new Push();

	    $FCM_return = 0;
	    $payload = array('dataa' => array('video_id' => "$video_id",
	        'device_type' => "$device_type",
	        'lock_mac' => "$lock_mac",
	        'btn_action' => "$btn_action"));

	    //$push->setIsBackground(FALSE);
	    $push->setPayload($payload);
	    //$push->setTitle($title);
	    //$push->setMessage($title);

	    $json = $push->getPush();
		
		$query     = "SELECT * FROM `vc_token` WHERE `video_id` = '$video_id'";
		$query_exe = $this->db->query($query);

	    if($query_exe->num_rows() > 0 ) {

		 	$vc_token_data =  $query_exe->result_array();

		 	foreach ($vc_token_data as $key => $value) {
		 		
		 		$device_id = $value['device_id'];
		 		$regId 	   = $value['device_token'];

		 		if (strlen($device_id) < 20) {
		 		    $push_res = $firebase->send($regId, $json, 'android');
		 		} else {
		 		    $push_res = $firebase->send($regId, $json, 'iso');
		 		}

	 	 		if(!empty($push_res) && $push_res == '1') {
	 	 			$FCM_return++;
	 	 		}
		 	}
		}

		if($FCM_return > 0) {
			return 'true';
		} else {
			return 'false';
		}
	}

	/*
		Author : Naresh Lakhara
		Date   : 05-04-2022
		Description   : iBell_Sync_Send_FCM
	*/
	public function iBell_Sync_Send_FCM($bell_ble_mac)
	{
	    // Enabling error reporting
	    // error_reporting(-1);
	    // ini_set('display_errors', 'On');
	    require_once APPPATH."third_party/firebase.php";
        require_once APPPATH."third_party/push.php";

	    $firebase = new Firebase();
	    $push = new Push();
	    $FCM_return = 'false';
	    $video_id = "";

	    $q1 = "SELECT * FROM `idoor_login` WHERE `device_ble_mac`='$bell_ble_mac'";
	    $query_exe = $this->db->query($q1);

	    if ($query_exe->num_rows() == 1) {

	        $row_login = $query_exe->row_array();
	        $video_id = $row_login['video_call_id'];

	        $payload = array('dataa' => array('video_id' => "$video_id",
	            'device_type' => "",
	            'lock_mac' => "",
	            'btn_action' => "sync"));

	        $push->setPayload($payload);
	        $json = $push->getPush();

	        $q2    = "SELECT * FROM `vc_token` WHERE `video_id` = '$video_id'";
	        $q2_exe = $this->db->query($q2);

	        if ($q2_exe->num_rows() > 0) {

	        	$data_get = $q2_exe->result_array();

	        	foreach ($data_get as $key => $row_vc_token) {
	        		
					$device_id = $row_vc_token['device_id'];
					$regId     = $row_vc_token['device_token'];

	                if (strlen($device_id) < 20) {
	                    $firebase->send($regId, $json, 'android');
	                } else {
	                    $firebase->send($regId, $json, 'iso');
	                }
	                $FCM_return = "true";
	        	}

	        } else {

	            $FCM_return = "false";
	        }
	    }
	    return $FCM_return;
	}
	public function sendNodeRequest($event_data)
	{
		try {

			$node_event_name = @$event_data['node_event_name'];
			// $event_name      = $event_data['event_name'] ? $event_data['event_name'] : "";
			// echo '<pre>'; print_r($event_data); exit;

			$client = new Client(new Version2X('http://' . NODE_IP . ':' . NODE_PORT));
			$client->initialize();

			$client->emit((string)trim($node_event_name), $event_data);
			// $client->emit('CONNECT_TO_ROOM', $event_data);

			$client->close();

		} catch (ServerConnectionFailureException $e) {

			echo  $e;
		}
	}
}
/* Location: ./application/models/common_model.php */