<?php
/**
 * Created by PhpStorm.
 * User: cpueblo
 * Date: 2016. 8. 30.
 * Time: 오후 4:56
 */
namespace platyFramework;

class ptyDBItemManager extends model
{
	var $pageLimit = 0;
	var $_tableName = "";

	public function __construct($tableName)
	{
		parent::__construct();
		$this->_tableName = $tableName;
	}

	function init()
	{
		$this->db->clear();
		$this->db->addFrom($this->_tableName);
		return $this;
	}

	function adminInit()
	{
		$this->db->clear();
		$this->db->addFrom($this->_tableName);
		return $this;
	}

	function getTotalCount()
	{
		GLOBAL $db;
		$this->db->clear()->addSelect("COUNT(*)")->addFrom($this->_tableName)->addWhere("enabled = '1'");
		return $this->db->getCount();
	}

	public function getItemById($id)
	{
		GLOBAL $db;
		$this->db->clear()->addSelect("*")->addFrom($this->_tableName)->addWhere("id = '$id'");

		$data = $this->db->sql_fetch();
		if (!$data)
			return null;

		$item = new ptyDBItem($this->_tableName, $data);
		return $item;
	}

	public function getItemBy($key, $value)
	{
		GLOBAL $db;
		$this->db->clear()->addSelect("*")->addFrom($this->_tableName)->addWhere("$key = '$value'");

		$data = $this->db->sql_fetch();
		if (!$data)
			return null;

		$item = new ptyDBItem($this->_tableName, $data);
		return $item;
	}

	public function getItemByArray($array)
	{
		$this->db->clear()->addSelect("*")->addFrom($this->_tableName);

		foreach ($array as $k => $v) {
			if ($k && $v)
				$this->db->addWhereEqual($k, $v);
		}

		$data = $this->db->sql_fetch();
		if (!$data)
			return null;

		$item = new ptyDBItem($this->_tableName, $data);
		return $item;
	}


	public function remove($id)
	{
		$this->db->clear()->addFrom($this->_tableName)->addWhere("id = '$id'")->addSet("enabled = 0")->update();
	}


	public function delete($id)
	{
		$this->db->clear()->addFrom($this->_tableName)->addWhere("id = '$id'")->delete();
	}

	public function add($data)
	{
		$this->db->clear()->addFrom($this->_tableName)->addSet($data)->insert();
		return $this->db->getInsertId();
	}

	function get($wheres = null, $orderBy = null)
	{
		$lst = $this->getRaw($wheres, $orderBy);
		$lst = ptyDBItem::buildWithItems($lst);
		return $lst;
	}

	function getRaw($wheres = null, $orderBy = null)
	{
		$this->init();
		if ($this->pageLimit)
			$this->db->setLimit($this->pageLimit);

		foreach ($wheres as $k => $v) {
			if (isset($k) && isset($v) && !is_null($v)) {
				$this->db->addWhereEqual($k, $v);
			}
			else if (isset($k)) {
				$this->db->addWhere($k);
			}
		}

		if (is_null($orderBy))
			$this->db->addOrderBy("id desc");
		else
		{
			foreach ($orderBy as $o)
				$this->db->addOrderBy($o);
		}

		$this->totalCount = $this->getTotalCount();

		// echo "totalCnt = ".$this->totalCount;
		$lst = $this->db->addSelect($this->_tableName . ".*")->sql_list();
		return $lst;
	}

	function getPaging()
	{
		if ($this->pageLimit == 0) return;

		// pg ==> board paging
		$page = (int)$this->request->request['pg'];
		if ($page == 0)
			$page = 1;

		$p = new Paginator($this->totalCount, $this->pageLimit, $page, '');
		$p->setMaxPagesToShow($this->pageLimit);

		$first = ptyRebuildUrl(array("pg" => 1));
		$prev = ptyRebuildUrl(array("pg" => $p->getPrevPage() ? $p->getPrevPage() : 1));
		$next = ptyRebuildUrl(array("pg" => $p->getNextPage() ? $p->getNextPage() : $p->getNumPages()));
		$last = ptyRebuildUrl(array("pg" => $p->getNumPages()));

		$out = "<a href='$first' class='first'>처음</a>";
		$out .= "<a href='$prev' class='prev'>이전</a>";

		foreach ($p->getPages() as $item) {
			$url = ptyRebuildUrl(array("pg" => $item['num']));
			if ($item[isCurrent])
				$out .= "<a href='$url' class='on'>" . $item[num] . "</a>";
			else
				$out .= "<a href='$url'>" . $item[num] . "</a>";
		}
		$out .= "<a href='$next' class='next'>다음</a>";
		$out .= "<a href='$last' class='last'>마지막</a>";
		return $out;
	}

	function getCurrentPageNo()
	{
		if ($this->pageLimit == 0) return 1;

		// pg ==> board paging
		$page = (int)$this->request->request['pg'];
		if ($page == 0) $page = 1;

		$p = new Paginator($this->totalCount, $this->pageLimit, $page, '');
		$p->setMaxPagesToShow($this->pageLimit);
		return $p->getCurrentPage();
	}

	function hasMorePaging()
	{
		if ($this->pageLimit == 0) return false;

		// pg ==> board paging
		$page = (int)$this->request->request['pg'];
		if ($page == 0) $page = 1;

		$p = new Paginator($this->totalCount, $this->pageLimit, $page, '');
		$p->setMaxPagesToShow($this->pageLimit);

		if ($p->getCurrentPage() != $p->getNumPages())
			return true;
		else
			return false;

	}
}

class ptyDBItem extends ptyItem
{
	var $db;
	var $tableName = "";

	public function __construct($tableName, $item = "")
	{
		GLOBAL $platyFramework;

		$this->db = $platyFramework->db;
		parent::__construct($item);
		$this->tableName = $tableName;
		$this->init();
	}

	public static function buildItemById($tableName, $id)
	{
		$item = new static($tableName);
		// $item->db->setDebug(1);
		$item->db->clear()->addSelect("*")->addFrom($item->tableName)->addWher("id = '$id'");
		$data = $item->db->sql_fetch();
		if (!$data)
			return null;

		$item->_item = $data;
		return $item;
	}

	public static function buildItemBy($tableName, $by, $value)
	{
		$item = new static($tableName);
		$item->db->clear()->addSelect("*")->addFrom($item->tableName)->addWhere("$by = '$value'");
		$data = $item->db->sql_fetch();
		if (!$data)
			return null;

		$item->_item = $data;
		return $item;
	}

	public function init()
	{
		$this->db->clear();
		return $this;
	}


	public function insert()
	{
		$this->db->clear()
			->addFrom($this->tableName)
			->addSet($this->_item)
			->insert();

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

	public function update()
	{
		GLOBAL $db;

		$this->db->clear();

		foreach ($this->_item as $k => $v) {
			if (!isset($v)) $v = '';

			if ($k == "id")
				continue;
			$this->db->addSet($k, $v);
		}

		$this->db->addFrom($this->tableName)
			->addWhereEqual("id", $this->id)
			->update();
	}
}

/**
 * Class ptyItem
 *
 * Getter 와 Setter 를 배열에서 객체로 변환하여 사용하게 합니다.
 * 주의 : 없는 변수에 대해서는 null 이 아닌 "" 를 리턴합니다
 *
 * @package platyFramework
 * @author cpueblo <cpueblo@platyhouse.com>
 */

abstract class ptyList
{
	protected $_items;

	public function __construct($lst)
	{
	}

	public function getCount()
	{
		return count($this->_items);
	}

	public function getItems()
	{
		return $this->_items;
	}

	public function getArrayItems()
	{
		$ret = array();
		foreach ($this->_items as $item) {
			$ret[] = $item->_item;
		}
		return $ret;
	}

	public function addLists($n)
	{
		if (!isset($this->_items))
			$this->_items = array();

		$this->_items = array_merge($this->_items, $n->_items);
	}

	public function addItem($item)
	{
		$this->_items[] = $item;
	}
}