<?php
/**
 * config_model.php - Model file for config system
 *
 * @author $Author: dtong $
 * @version $Id: config_model.php,v 1.9 2011/02/22 13:49:10 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/

Class Config_model extends CI_Model {

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

   function get_allconfig($index=FALSE) {
		$this->db->select('*');
		$this->db->from('app_config');
		if ( $index !== FALSE ) {
			if (!osa_is_int($index)) {
				return FALSE;
			}
			$this->db->where('system', $index);
		}
		$resobj = $this->db->get();
		if ( $resobj->num_rows() <= 0 ) {
			return FALSE;
		}
   	$result = $resobj->result();
   	if ( !$result ) {
   		return FALSE;
   	}
   	$ret = array();
   	foreach($result as $record) {
   		$value = json_decode($record->value);
   		//PHP 5.2 does not support json_last_error()
   		if ( function_exists('json_last_error') ) {
	   		if ( json_last_error() === JSON_ERROR_NONE ) {
					$ret[$record->item] = $value;
	   		}
   		}
   		else {
   			$ret[$record->item] = $value;
   		}
   	}
   	return $ret;
   }

   function update($index, $item, $value) {
   	if ( !osa_is_int($index) ) {
   		return FALSE;
   	}
   	$value = (json_encode($value));
   	if ( function_exists('json_last_error') ) {
	   	if ( json_last_error() != JSON_ERROR_NONE ) {
	   		return FALSE;
	   	}
   	}
		$this->db->select('*');
		$this->db->from('app_config');
		$this->db->where('item', $item);
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 ) {
			$data = array('item'=>$item, 'value'=>"$value", 'system'=>$index);
			return $this->db->insert('app_config', $data);
		}
		else {
			$data = array('value'=>"$value", 'system'=>$index);
			$this->db->where('item', $item);
			return $this->db->update('app_config', $data);
		}
   }

   function delete($item) {
   	$this->db->where('item', $item);
   	return $this->db->delete('app_config');
   }

   //Clears all the sessions records.
   //This just kicks everyone out from the site.
   function clear_ci_sessions($keep_sessions=FALSE) {
   	if ( $keep_sessions ) {
   		$this->db->where_not_in('session_id', $keep_sessions);
   	}
   	return $this->db->delete('ci_sessions');
   }
}