<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class guest_mapper
{
	protected $allowedKeys=array('name', 'email', 'msg', 'answer', 'ip', 'putdate', 'user_id');

	public function getPosts(&$count, $perPage=10, $page=1)
	{
		$data= Db::i()->selectPage(
			$count, 
			"SELECT msg_id
			FROM ?_guest
			ORDER BY msg_id DESC
			LIMIT ?d, ?d",
			($page-1)*$perPage, $perPage
		);
		$result=array();
		if ($data) {
			foreach ($data as $item) {
				$result[]=$item['msg_id'];
			}
		}
		return $result;
	}
	
	public function getPostsByArrayId($id)
	{
		$result=Db::i()->select(
			"SELECT *
			FROM ?_guest
			WHERE msg_id IN(?a)
			ORDER BY FIELD(msg_id, ?a)",
			$id, $id
		);

		$data=array();
		if ($result) {
			foreach ($result as $item) {
				$item['ip']=inet_ntop($item['ip']);
				$obj=Factory::create('guest.post_entity', $item);
				$data[$obj->id]=$obj;
			}
		}
		return $data;
	}
	
	public function addPost($post)
	{
		$insert=$post->getFilteredKeys($this->allowedKeys);
		$insert['ip']=inet_pton($insert['ip']);

		return Db::i()->query(
			"INSERT INTO ?_guest (?#) VALUES(?a)",
			array_keys($insert),
			array_values($insert)
		);
	}
	
	public function deletePost($post)
	{
		return Db::i()->query("DELETE FROM ?_guest WHERE msg_id=?", $post->id);
	}
	
	public function updatePost($post)
	{
		$data=$post->getFilteredKeys($this->allowedKeys);
		if ($data['ip']) $data['ip']=inet_pton($data['ip']);
		
		return Db::i()->query("UPDATE ?_guest SET ?a WHERE msg_id=?", $data, $post->id);
	}
}