<?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 feedback_mapper
{
	public function getFormDataById($tree_id)
	{
		$data=Db::i()->select("SELECT * FROM ?_feedback_form WHERE tree_id=? ORDER BY position", $tree_id);
		foreach ($data as $key => $value) {
			$tmp=unserialize($value['options']);
			$data[$key]=array_merge($value, $tmp);
		}
		
		return $data;
	}

	public function addElement($tree_id, $data)
	{
		$id=Db::i()->query("INSERT INTO ?_feedback_form (tree_id, options) VALUES(?, ?)", $tree_id, serialize($this->_parseArray($data)));
		Db::i()->query("UPDATE ?_feedback_form SET position=id WHERE id=?", $id);
	}

	public function updateElement($id, $data)
	{
		Db::i()->query("UPDATE ?_feedback_form SET options=? WHERE id=?", serialize($this->_parseArray($data)), $id);
	}

	protected function _parseArray($array)
	{
		$data=array(
			'type'=>$array['type'],
			'title'=>$array['title'],
			'required'=>$array['required'],
			'options'=>empty($array['options'])?null:$array['options']
		);
		return $data;
	}

	public function move_up($id)
	{
		if ($data=$this->getElementById($id)) {
			if (
				$prevous_id=Db::i()->selectCell(
					"SELECT id FROM ?_feedback_form WHERE tree_id=? AND position<? ORDER BY position DESC LIMIT 1", $data['tree_id'], $data['position']
				)
			) {
				$this->swapRows($id, $prevous_id);
			}
		}

	}

	public function move_down($id)
	{
		if ($data=$this->getElementById($id)) {
			if (
				$next_id=Db::i()->selectCell(
					"SELECT id FROM ?_feedback_form WHERE tree_id=? AND position>? ORDER BY position ASC LIMIT 1", $data['tree_id'], $data['position']
				)
			) {
				$this->swapRows($id, $next_id);
			}
		}

	}

	public function getElementById($id)
	{
		$data=Db::i()->selectRow("SELECT * FROM ?_feedback_form WHERE id=?", $id);
		$tmp=unserialize($data['options']);
		$data=array_merge($data, $tmp);
		return $data;
	}

	public function delete($id)
	{
		Db::i()->query("DELETE FROM ?_feedback_form WHERE id=?", $id);
	}

	protected function swapRows($id1, $id2)
	{
		Db::i()->query(
			"UPDATE ?_feedback_form t1
			JOIN ?_feedback_form t2
			ON t1.id=? AND t2.id=?
			SET
			t1.position=t2.position,
			t2.position=t1.position",
			$id1, $id2
		);
	}
}