<?php
/**
 * appintegrator_model.php class file
 *
 * @package			AIR\Models
 * @version			V2.7.0
 * @copyright		2015, BizyCorp Internal Systems Development
 * @license			private, All rights reserved
 * @author			MRM Roshan <roshan@ekwa.com>
* 
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This model file maintains tables of application integration informations
 *
 * Functions available :-
 * 		function __construct() - class constructor
 * 		function exists() - checks for existing primary key
 * 		function getArray() - gets table header array
 * 		function getHeader() - gets record column information
 * 		function get_data() - gets recrdset
 * 		function set_query() - sets query to quiry the table
 * 		function count_data() - counts the record set 
 * 		function save() - saves submitted data
 * 		function delete() - deletes records
 * 		function getMetadata() - gets table column information
 * 		function get_app_data() - gets application data from db 

 *  Creation date     :- Jun 5, 2014
 *	Last Modified on  :-
 * 	Last Modification :-
 * 
 * @package    AIR\Models
 * @author     Mohamed Ruzaik Mohamed Roshan <roshan@ekwa.com>
 * @version    V 2.7.0
 * @created    Jun 5, 2014
 */
class AppIntegrator_model extends CI_Model{

	/**
	 * $metadata_array
	 * 
	 * @var array
	 */
	protected $metadata_array = array();
	
	/**
	 * Abstract __construct function
	 *
	 * Meta Information will be generated at the class initialization
	 */	
	function __construct(){
		
		parent::__construct();
		/**
		 * @$metadata_array - stores the added field comments,type and lenght of all 
		 * the required fields for the model
		 */
		$this->metadata_array['PK'] = 'integration_id';
		
		$this->metadata_array['integration_id']['header']= 'Integration Id';
		$this->metadata_array['integration_id']['type']= 'int';
		$this->metadata_array['integration_id']['width']='100';
		
		
		$this->metadata_array['intergration_name']['header']='Integration Name';
		$this->metadata_array['intergration_name']['type']= 'text';
		$this->metadata_array['intergration_name']['width']='250';
		
		$this->metadata_array['calling_app_id']['header']='Calling App Id';
		$this->metadata_array['calling_app_id']['type']= 'int';
		$this->metadata_array['calling_app_id']['width']='100';
		
		$this->metadata_array['calling_app_access_key']['header']='Calling App Access Key';
		$this->metadata_array['calling_app_access_key']['type']= 'varchar';
		$this->metadata_array['calling_app_access_key']['width']='45';
		
		$this->metadata_array['calling_app_secret_key']['header']= 'Calling App Secret Key';
		$this->metadata_array['calling_app_secret_key']['type']= 'varchar';
		$this->metadata_array['calling_app_secret_key']['width']='45';
		
		$this->metadata_array['called_app_id']['header']='Called App Id';
		$this->metadata_array['called_app_id']['type']= 'int';
		$this->metadata_array['called_app_id']['width']='100';
		
		$this->metadata_array['called_app_access_key']['header']='Called App Access Key';
		$this->metadata_array['called_app_access_key']['type']= 'varchar';
		$this->metadata_array['called_app_access_key']['width']='45';
		
			
		$this->metadata_array['called_app_secret_key']['header']='Called App Secret Key';
		$this->metadata_array['called_app_secret_key']['type']= 'varchar';
		$this->metadata_array['called_app_secret_key']['width']='45';
		
		$this->metadata_array['added_by']['header']='Added By';
		$this->metadata_array['added_by']['type']= 'int';
		$this->metadata_array['added_by']['width']='11';
		
		$this->metadata_array['added_date_time']['header']='Added Date & Time';
		$this->metadata_array['added_date_time']['type']= 'date';
		$this->metadata_array['added_date_time']['width']='';
		
		$this->metadata_array['updated_by']['header']='Updated By';
		$this->metadata_array['updated_by']['type']= 'int';
		$this->metadata_array['updated_by']['width']='11';
		

		$this->metadata_array['updated_date_time']['header']='Updated Date & Time';
		$this->metadata_array['updated_date_time']['type']= 'date';
		$this->metadata_array['updated_date_time']['width']='';
				
		$metadata = $this->db->field_data('ar_applications') ;
		
		foreach($metadata as $column){
			
			if (!isset($this->metadata_array[$column->name])) {
				
				$this->metadata_array[$column->name]['header'] =  $column->name ;
				$this->metadata_array[$column->name]['type'] = $column->type ;
				$this->metadata_array[$column->name]['width'] = $column->max_length ;
			}
		}
	}//end of function
		
	
	/**
	 * exists() function
	 *
	 * Checks whether given entity exists in database or not
	 *
	 * @param $primekey is an array of key field and value, starting index of dataset, useful for pagination etc
	 *		  Ex: Array($field_name=>value);
	 * @return TRUE if exists, FALSE if not
	 */
	function exists($primekey){	
		
		$this->db->from('ar_applications');
		foreach ($primekey as $k=>$v){
			$this->db->where($k,$v);
		}
		$query = $this->db->get();

		return ($query->num_rows()>=1);
		
	}


	/**
	 * getArray() function
	 *
	 * converts database query resultset to an associative array
	 *
	 * @param $result, the database resultset
	 *
	 * @return An associative array of resultset and associate db table field comments
	 *
	 */
	private function getArray($data){	
		
		
		$out = array();
		$ix = 1;

		foreach($data as $row){
			foreach($row as $k => $v )	{
				$out[$ix][$k] = $v ;
			}
		
			$ix++;
		}
		
		return $out;
		
	}//end of function
		
	
	/**
	 * getHeader() function
	 *
	 * This is a standard model function to get table column information
	 *
	 * @param array $data
	 *
	 * @return array record set
	 */	
	private function getHeader($data){
		
		if(isset($data['selection'])){
			
			$selection =   $data['selection'];
		}else{
			
			$selection = 
					    'ar_applications.integration_id,
					    ar_applications.intergration_name,
						ar_applications.calling_app_id,
						ar_applications.calling_app_access_key,
						ar_applications.calling_app_secret_key, 				
						ar_applications.called_app_id,
						ar_applications.called_app_access_key,
						ar_applications.called_app_secret_key,
						ar_applications.added_by,
						ar_applications.added_date_time,
					    ar_applications.updated_by,
						ar_applications.updated_date_time' ;
		}//end if
		
		 
		$selection_array= array();
		
		$selection_array=explode(",",$selection);
		
		$out['PK']=$this->metadata_array['PK'];
		
		foreach($selection_array as $t_field){
			
			//var_dump($t_field);
			$field=explode(".",$t_field);
			if($field[1] =='*'){
				$out=$this->metadata_array;
				break;
			}else{
				$out[$field[1]]['header']=$this->metadata_array[$field[1]]['header'];
				$out[$field[1]]['type']=$this->metadata_array[$field[1]]['type'];
				$out[$field[1]]['width']=$this->metadata_array[$field[1]]['width'];
			}
			
		}//endfor each
		
		return $out;
		
	}//end of function
	
		
	/**
	 * get_data() function
	 *
	 * gets complete data from the table with the facility of selection and filters.Records can be grouped and ordered
	 *
	 * @param $data is a composit array with elements for
	 * 				selection - fields that are to be selected / default *, filter - the conditions for where clause,
	 * 				group by , having and order by Ex: Array(
	 * 				['selection']=>'table_name.field_name1,table_name.field_name2',
	 * 				['filter']=>array(field_name=>value),
	 * 				['group_by']=>'field_name1,field_name2',
	 * 				['having']=>array(filed_name => value) ,
	 * 				['order_by']=>array(filed_name => order));
	 *				['order_by']=>array(filed_name => order) - order is asc/desc
	 *
	 * 			$data['search'] is a an associative array
	 * 		    will have the field, value and query method as array object
	 * 			array('search_field' => $field, 'search_text' => $search_text,'query_method'=>$query_method);
	 * 		  	search_field=> table field name
	 * 		  	search_text=> text / id to be searched
	 * 		  	query_method=> equal/like the query method to be used for the search
	 *
	 * @return All data, as an associative array with use of getArray() function
	 */		
	function get_data($data){
		
		$out = array();
				
		if(isset($data['limit']) && $data['limit'] !="" && $data['limit'] !="0"){
			$limt_enabled=true;
				
		}else{
			$limt_enabled=false;
				
		}
		
	  $header=$this->getHeader($data);
	  $total_num_records = $this->count_data($data);
	
	  $this->set_query($data,$limt_enabled);
	  
	  
      $query = $this->db->get();
      //var_dump($this->db->last_query());exit();
      log_message('info',"SQL in get_data() :-".$this->db->last_query());
      $result = $this->getArray($query->result());
      
      $out['metadata']=$header;
      $out['total_rows']= $total_num_records;
      $out['result_set'] = $result;
	  //var_dump($result);
      log_message('info', "variable value of \$out in get_data():-".serialize($out));
      return $out;     
  	  
	}//end of function
		
	
	/**
	 * set_query() function
	 *
	 * This function is a standard model function. It sets query string to retrive table records based on given params
	 *
	 * @param array $data
	 * @param bool $limit_enable
	 */	
	function set_query($data,$limit_enable){
	
		$search_filter=array(array(
				'search_field' => 'ar_applications.integration_id', 
				'search_text' => '',
				'query_method'=>''));
		
		if(isset($data['selection'])){
				
			$selection =   $data['selection'];
		}else{
				
			$selection = 
					   'ar_applications.integration_id,
					   	ar_applications.intergration_name,	
						ar_applications.calling_app_id,
						ar_applications.calling_app_access_key,
						ar_applications.calling_app_secret_key, 				
						ar_applications.called_app_id,
						ar_applications.called_app_access_key,
						ar_applications.called_app_secret_key,
						ar_applications.added_by,
						ar_applications.added_date_time,
					    ar_applications.updated_by,
						ar_applications.updated_date_time' ;
		}//end if
		
		
		
		$data['search'] = isset($data['search'])  ? $data['search'] : $search_filter ;
		//var_dump($data['selection']);
		
		//added by Dinishika
		$this->db->from('ar_applications');
		
		
				
		if (isset($data['selection'])) {
			//var_dump($data['selection']);
			$this->db->select($data['selection']); // TODO check and implement
		}
		
		//var_dump($data['search']);exit;//added by Dinishika
		
		if(isset($data['search'])&& $data['search']!=null) {
			
			foreach($data['search'] as $s)
			{
                //var_dump($s['query_method']);
				if($s['query_method'] == "equal"){
					$this->db->where($s["search_field"],$s["search_text"]);
				}elseif ($s['query_method'] == "like"){
					$this->db->like($s["search_field"],$s["search_text"]);
				}elseif($s['query_method'] == "or_like"){
					$this->db->or_like($s["search_field"],$s["search_text"]);
				}elseif($s['query_method'] == "not_like"){
					$this->db->not_like($s["search_field"],$s["search_text"]);
				}
			}
		}
		
	
		if (isset($data['group_by'])){
			 
			$this->db->group_by($data['group_by']);
		
		}
		
		if (isset($data['having'])){
		
			foreach($data['having'] as $c=>$v)
			{
				$this->db->having($c,$v);
			}
		
		}
		
		if (isset($data['order_by'])){
			foreach($data['order_by'] as $c=>$v)
			{
				$this->db->order_by($c,$v);
			}
			 
		}
		
		if($limit_enable == true){
  			if (isset($data['limit'])){
  		  		$this->db->limit($data['limit'],$data['offset']) ;
  			}
		}
		
		
	}//end of function
	
		
	/**
	 * count_data() function
	 *
	 * gets complete data from the table with the facility of selection and filters. Then counts returned records	 
	 *
	 * @param $data is a composit array with elements for
	 * 				selection - fields that are to be selected / default *, filter - the conditions for where clause,
	 * 				group by , having and order by
	 * 				Ex: Array(['selection']=>'table_name.field_name1,table_name.field_name2',
	 * 				['filter']=>array(field_name=>value),
	 * 				['group_by']=>'field_name1,field_name2',
	 * 				['having']=>array(filed_name => value) ,
	 * 				['order_by']=>array(filed_name => order));
	 *				['order_by']=>array(filed_name => order) - order is asc/desc
	 *
	 * @return All data, as an associative array with use of getArray() function
	 */
	function count_data($data){
		        
      	$this->set_query($data,false);
		return $this->db->count_all_results();	
			
	}//end of function
	
	
	/**
	 * save() function
	 *
	 * Insert data as a new record, if not exists, otherwise do Update
	 *
	 * @param array $ar_application_data array
	 * @param $key an array of key field names and values
	 *
	 * @return status of Query execution , TRUE if successful, otherwise FALSE
	 *
	 */	
	function save(&$ar_applications_data,$key=false){

		//var_dump($ar_applications_data);
		
		if (!$this->session->userdata('user_id')){
			//show_error('No user identification given! progressbar data not saved',$status_code=500) ;
			//return false;
			$ar_applications_data['added_by']=1;
		} else {
			$ar_applications_data['added_by']=  $this->session->userdata('user_id');
		
		}
    	// set the data from the passed array
   
    	foreach($ar_applications_data as $c=>$v){
    		
			$this->db->set($c,$v);
		}
    	
		//If key passed set key fields and creation date and insert		
		if (!$key or !$this->exists($key)){
			 
      		
      		foreach($key as $c=>$v){
  				$this->db->set($c,$v);
  			}
      		
       		$this->db->set('added_date_time','now()',FALSE);

			if($this->db->insert('ar_applications')){
				return $this->db->insert_id();
			}
				return false;
		}
		
		//If not Set filter for primary key & modifide datetime and update
		if ($this->session->userdata('user_id')){
			$this->db->set('updated_by', $this->session->userdata('user_id'),FALSE);
		}else{
			$this->db->set('updated_by', 1,FALSE);
		}	
    	$this->db->set('updated_date_time','now()',FALSE);
	
  		foreach($key as $c=>$v){  			
			$this->db->where($c,$v);
		}
		
		return $this->db->update('ar_applications');
		
	}//end of function
	
	
	/**
	 * delete() function
	 * 
	 * Delete record(s) from table
	 *
	 * @param $pk an array of data PK values of the relevant record	array($pk=>$value);	(field_name=>value)
	 *
	 * @return status of Query execution , TRUE if successful, otherwise FALSE
	 */	
	function delete($pks){		
		
		$this->db->where($pks);
		$this->db->delete('ar_applications');
		return $this->db->affected_rows();	
		
 	}//end of function

 	
 	/**
 	 * getMetadata() function
 	 *
 	 * This function will retun the Metadata array for the use of the controller a any other purpose
 	 * 
 	 * @return bool
 	 */ 	
  public function getMetadata() {
  	    
    If (isset($this->metadata_array)) {
      return $this->metadata_array;
    }else {
      return false;
    }
  } //end of function
  
  
  /**
   * get_app_data($integration_id,$calling_app_id,$called_app_id,$calling_app_func_id)
   * 
   * This method gets application information from db for given parameters
   * 
   * @param int $integration_id
   * @param int $calling_app_id
   * @param int $called_app_id
   * @param int $calling_app_func_id
   * @return array
   */
  public function get_app_data($integration_id,$calling_app_id,$called_app_id,$calling_app_func_id){
  	
  	$this->db->select('*');
  	$this->db->from('ar_applications');
  	$this->db->where(array(
  				'integration_id' => $integration_id,
  				'calling_app_id'=> $calling_app_id,
  				'called_app_id'=>$called_app_id,
  				'calling_app_function_id' =>$calling_app_func_id)
  	);
  	$query = $this->db->get();  	
  	$result = $query->result();
  	return $result;
  	
  }//end of function
  
  
}//end of class
?>