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

class General extends CI_Model {

	function __construct() {
		parent::__construct();
	}

	public function fetchAll($table, $select = array('*'), $where = array(), $join = array(), $order = array()) {
		if(!$table) return NULL;
			
		if ($select) 	foreach($select as $key => $value) $this->db->select($value,false);
		if ($where) 	foreach($where as $key => $value) $this->db->where($key,$value);
		if ($join) 		foreach($join as $key => $value) $this->db->join($value[0],$value[1],$value[2],false);
		if ($order)		foreach($order as $key => $value) $this->db->order_by($key, $value);
		
		$query = $this->db->get($table);
		
		return ($query->num_rows() > 0) ? json_decode(json_encode($query->result()),true) : null;
	}

	public function fetchSingle($table, $select = array('*'), $where = array(), $join = array(), $order = array()) {
		$query = $this->fetchAll($table, $select, $where, $join, $order);
		
		return ($query) ? $query[0] : NULL;
	}
	
	public function fetchQuery($sql, $single = false) {
		if(!$sql) return NULL;
		
		$r = $this->db->query($sql);
		$result = ($r) ? $r->result() : NULL;
		
		if($single) $result = $result[0];
		
		return ($result) ? json_decode(json_encode($result),true) : NULL;
	}

	public function insert($table,$data){
		if (!$table) return NULL;
		
		$this->db->insert($table, $data);
		return ($this->db->affected_rows() > 0) ? $this->db->insert_ID() : NULL;
	}
	
	public function update($table, $data, $where) {
		if (!$table) return NULL;
		if ($where) foreach($where as $key => $value) $this->db->where($key,$value,false);
		
		$query = $this->db->update($table, $data);
		return ($query === TRUE) ? TRUE : FALSE;
	}
	
	public function delete($table, $where) {
		if (!$table) return NULL;
		if ($where) foreach($where as $key => $value) $this->db->where($key,$value);
		
		$query = $this->db->delete($table);
		return ($query === TRUE) ? TRUE : FALSE;
	}
	
	public function lastInsertID() { return $this->db->insert_ID; }
	
}

