<?php

class RCMS_Object_Template_TemplateModel extends RCMS_Core_BaseModel {
	
	/**
	 * The name of table in the database.
	 * @var string
	 */
	protected $table = 'template';

	/**
	 * This function selects data by id.
	 * @param inetger $id
	 * @return object
	 */
	public function selectTemplateById($id)
	{		
		$select = $this->_adapter->select()->from($this->table)->where('id = ?', $id);		
		return $select->query()->fetchObject();	
	}

	/**
	 * This function selects data by name of template.
	 * @param string $templateName
	 * @return object
	 */
    public function selectTemplateByName($templateName)
	{
		$select = $this->_adapter->select()->from($this->table)->where('name = ?', $templateName);
		return $select->query()->fetchObject();
	}
	
	/**
	 * Insert new template into the database.
	 * @param object RCMS_Object_Template_Template $template
	 * @return integer
	 */
	public function insertTemplate(RCMS_Object_Template_Template $template)
	{
		$data = array (
			'name'			=> $template->getName(),
			'content'		=> $template->getContent(),
			'preview_path'	=> $template->getPreviewImage(),
			'theme_name'	=> $template->getTheme()
		);
		
		$this->_adapter->insert($this->table, $data);		
		return $this->_adapter->lastInsertId($this->table);	
	}
	
	/**
	 * Update the template.
	 * @param object RCMS_Object_Template_Template $template
	 * @return integer
	 */
	public function updateTemplate(RCMS_Object_Template_Template $template)
	{
		$data = array (
			'name'			=> $template->getName(),
			'content'		=> $template->getContent(),
			'preview_path'	=> $template->getPreviewImage(),
			'theme_name'	=> $template->getTheme()
		);
		
		$where =  sprintf("id = %d", $template->getId());
		 
		return $this->_adapter->update($this->table, $data, $where);		
	}
	
	/**
	 * Delete the template.
	 * @param integer $id
	 * @return integer
	 */
	public function deleteTemplate($id)
	{
		$where = sprintf("id = %d", $id);
		return $this->_adapter->delete($this->table, $where);
	}
}
