<?php

/**
 * class.db.php
 * author:rok kelvišar
 */

class Db {
	public $x = '';
	//public $database;
	
	public function __construct() {
		global $settings;
		
		$this->database = $settings['db'];
		mysql_connect($this->database['host'], $this->database['username'], $this->database['password']) or die(mysql_error());
		mysql_select_db($this->database['database']) or die(mysql_error());		
		mysql_query("SET NAMES 'utf8'") or die(mysql_error());
		mysql_query("SET lc_time_names = 'sl_SI'") or die(mysql_error());
	}
	
	public function select($arr, $is_sql_statement = true,$debug = null) {
		if ($debug) dump($arr);
		if (!$is_sql_statement) {
			$sql = "SELECT ";
			
			foreach ($arr['fields'] as $key => $field) {
				$fields .= ',' . $field;
			}
			$fields = substr($fields,1);
			$sql .= $fields;
			$sql .= " FROM " . $arr['table'];
			if (isset($arr['where'])) {
				$sql .= " WHERE " . $arr['where'];			
			}
			if (isset($arr['order'])) {
				$sql .= " ORDER BY " . $arr['order'];			
			}
		} else {
			$sql = $arr;
		}
		//dump($sql);
		$result = mysql_query($sql) or die(mysql_error()); 
		if ($result) {
			while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
			return $resultArray;
		} else {
			return false;
		}
	}
	
	public function save($sql) {
		//dump($sql);
		return (mysql_query($sql)) ? mysql_insert_id() : mysql_error();
	}
	
	public function update($sql) {
		return (mysql_query($sql) or die(mysql_error())) ? true : mysql_error();
	}
	
	public function query($sql) {
		$a = mysql_query($sql);
		$this->affected = mysql_affected_rows();
		return ($a) ? true : false;		
	}
	
	public function log($action,$data) {
		$sql = "INSERT INTO watchdog SET action ='{$action}', data='{$data}'";
		$this->save($sql);
		return $sql;
	}
	
	public function showLog($action='',$data='') {
		$sql = "SELECT * FROM watchdog ORDER BY timestamp DESC";
		$log = $this->select($sql);
		krumo($log);
		$table = '<table class="list">';
		foreach ($log as $record) {
			$table .= "<tr>";
			foreach ($record as $key => $value) {
				$field = '';
				if ($record = json_decode($value)) {
					if (!empty($record) && (is_array($record) || is_object($record))) {
						//dump($record);
						foreach ($record as $json_key => $json_value) {
							$field .= "<td title='{$json_key}'>{$json_value}</td>";
						}
					} else {
						$field .= "<td title='{$key}'>{$value}</td>";
					}
				} else {
					$field = "<td title='{$key}'>{$value}</td>";
				}
				$table.=$field;
			}
			$table .= "</tr>";
			
			//dump($record);
		}
		$table .= '</table>';
		$this->watchdog->_render = $table;
		$this->watchdog->raw = $log;
		
		return $this->watchdog->_render;
	}
}

$oDb = new Db();
?>