<?php
class Feedbacks extends Buyers
{

	public function get_feedback($id)
	{
		$query = $this->db->placehold("SELECT * FROM feedbacks WHERE id=? LIMIT 1", intval($id));

		if($this->db->query($query))
			return $this->db->result();
		else
			return false;
	}

	public function get_feedbacks($filter = array())
	{
		// По умолчанию
		$limit = 0;
		$page = 1;
		$type = '';
		$keyword_filter = '';

		if(isset($filter['limit']))
			$limit = max(1, intval($filter['limit']));

		if(isset($filter['page']))
			$page = max(1, intval($filter['page']));

		if(isset($filter['type']))
			$type = $this->db->placehold('AND type in(?@)', (array)$filter['type']);

		$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);

		if(!empty($filter['keyword']))
		{
			$keywords = explode(' ', $filter['keyword']);
			foreach($keywords as $keyword)
				$keyword_filter .= $this->db->placehold(' AND (name LIKE ?~ OR message LIKE ?~ OR phone LIKE ?~ OR email LIKE ?~)', $keyword, $keyword, $keyword, $keyword);
		}

		$order = 'added';
		if(!empty($filter['sort']))
			switch ($filter['sort'])
			{
				case 'added':
				$order = 'added DESC';
				break;
				case 'name':
				$order = 'name';
				break;
			}

		$query = $this->db->placehold("SELECT * FROM feedbacks WHERE 1 $keyword_filter $type ORDER BY $order $sql_limit");

		$this->db->query($query);
		return $this->db->results();
	}

	public function count_feedbacks($filter = array())
	{
		$visible_filter = '';
		$type = '';
		$keyword_filter = '';

		if(isset($filter['visible']))
            $visible_filter = $this->db->placehold('AND visible = ?', intval($filter['visible']));

        if(isset($filter['type']))
			$type = $this->db->placehold('AND type in(?@)', (array)$filter['type']);

		if(!empty($filter['keyword']))
		{
			$keywords = explode(' ', $filter['keyword']);
			foreach($keywords as $keyword)
				$keyword_filter .= $this->db->placehold(' AND (name LIKE ?~ OR message LIKE ?~ OR phone LIKE ?~ OR email LIKE ?~)', $keyword, $keyword, $keyword, $keyword);
		}

		$query = $this->db->placehold("SELECT count(distinct id) as count
										FROM feedbacks WHERE 1 $visible_filter $type $keyword_filter");

		$this->db->query($query);
		return $this->db->result('count');

	}


	public function add_feedback($feedback)
	{
		$query = $this->db->placehold('INSERT INTO feedbacks SET ?%, added = NOW()', $feedback);
		if(!$this->db->query($query))
			return false;

		$id = $this->db->insert_id();
		return $id;
	}


	public function update_feedback($id, $feedback)
	{
		$query = $this->db->placehold("UPDATE feedbacks SET ?% WHERE id in(?@)", $feedback, (array)$id);
		$this->db->query($query);
		return $id;
	}


	public function delete_feedback($id)
	{
		if(!empty($id))
		{
			$query = $this->db->placehold("DELETE FROM feedbacks WHERE id=? LIMIT 1", intval($id));
			$this->db->query($query);
		}
	}
}
