<?php
// запрет прямого доступа
defined('_JEXEC') or die('Restricted access');

class db_controller{
	private $mysqli;
	private $host		= '94.130.51.218';
	private $user		= 'slackbot';
	private $pass		= 'zyvDndurDQZ2Savx';
	private $db_name	= 'slackbot';
	var $error = '';
	
	function __construct(){
		$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db_name);
		$this->mysqli->set_charset("utf8");
		if( $this->mysqli->connect_errno ){
			$this->error = $mysqli->connect_error;
			exit();
		}
	}
	function query($query){
		$rows = $this->mysqli->query($query);
		
		$result = array();
		if (gettype($rows) != 'boolean')
			while ($obj = $rows->fetch_object()) {
				$result[] = $obj;
			}
		
		return $result;
	}
	function update($arr, $table, $marker){
		$query	= "UPDATE ".$table.' SET ';
		
		$i = 0;
		foreach($arr as $key => $value){
			if ($key != $marker){
				if ($i > 0) $query .= ', ';
				$query .= "`$key` = ".$this->escapeString($value);
				
				$i++;
			}
		}
		$val = $arr->$marker;
		$query	.= " WHERE $marker='$val'";
		$rows	= $this->mysqli->query($query);	
		
		return $query;
	}
//	function insert($arr, $table){
//		$query	= "INSERT ".$table.' SET ';
//
//		$i = 0;
//		foreach($arr as $key => $value){
//			if ($i > 0) $query .= ', ';
//			$query .= "`$key` = ".$this->escapeString($value);
//
//			$i++;
//		}
//		$rows	= $this->mysqli->query($query);
//		file_put_contents(__DIR__ . '/log.txt', print_r($query,true));
//	}
	function insert($arr, $table){
		$query	= 'INSERT INTO '.$table.' (`sm_title`, `condition`, `mess`, `exception`, `attachment`, `state`) 
		VALUES ( "'.$arr->sm_title.'",'."'$arr->condition'".',"'.$arr->mess.'","'.$arr->exception.'","'.$arr->attachment.'","'.$arr->state.'" )';


		$rows	= $this->mysqli->query($query);
	}
	function delete($val, $table, $marker){
		$query	= "DELETE FROM ".$table;
		
		$query	.= " WHERE $marker=$val";
		$rows	= $this->mysqli->query($query);	
	}
	function escapeString($value){
		return  "'".mysqli_real_escape_string($this->mysqli, $value)."'";
	}
	function __destruct() {
		if ($this->mysqli)
			$this->mysqli->close();
	}
}