<?php
namespace Models;

// Модель логов
class Logs extends \DB\SQL\Mapper {
	public $db, $f3;

	public function __construct($db, $f3) {
		parent::__construct($db, 'logs' ); // подключаемся к таблице логов
		$this->db=$db;
		$this->f3=$f3;
	}

	// Выборка логов
	function select_log($query=null, $options=null) {
		$logs=array();
		// собственно сам запрос
		$this->load($query, $options);
		if($this->dry()) {
			return $logs;
		}
		do {
			$logs[]=$this->cast();
		}
		while($this->skip());
		$this->reset();
		return $logs;
	}

	// Удаление логов
	function delete_log($query=null) {
		// собственно сам запрос
		if($this->erase($query)===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'delete_successful'
		);
	}

	// Список логов
	function logs_list($start=0, $limit=30) {
		$where='id>?';
		$val=array(0);
		$logs=$this->select_log(array($where, $val), array('order'=>'read, time DESC', 'offset'=>$start, 'limit'=>$limit));
		$sql="SELECT COUNT(*) AS count FROM logs AS r WHERE ".$where;
		$res=$this->db->exec($sql, $val);
		$count=$res[0]['count'];

		return array(
			'success'=>true,
			'count'=>$count,
			'logs'=>$logs
		);
	}

	//Добавляем запись
	function save_log($txt) {
		$this->reset();
		$this->txt=strip_tags($txt, '<br><p><a>');
		$this->time=time();
		if($this->save()===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}

		return array(
			'success'=>true,
			'txt'=>'save_successful'
		);
	}

	// Изменяем метку о чтении лога
	function read($id) {
		if(!$id) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}

		$this->reset();
		$this->load(array('id=?', $id), array('limit'=>1));
		if($this->dry()) {
			return array(
				'success'=>false,
				'txt'=>'not_found'
			);
		}

		$this->read=abs($this->read-1);
		if($this->update()===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'close_all_window'=>true
		);
	}

	// Изменяем метку о чтении лога
	function read_all() {
		$res=$this->db->exec(array("UPDATE logs SET read=1"));
		if($res===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}

		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'close_all_window'=>true
		);
	}

	function cleaning_logs($sinch=0) {
		if($sinch=0) {
			$sinch=$this->db->exec("SELECT logs FROM synchronization LIMIT 1");
			$sinch=$sinch[0]['logs'];
		}
		$this->db->exec("DELETE FROM logs WHERE time<?", min($sinch, time()-24*3600*3));
	}
}
