<?php defined('_JEXEC') or die();
/**
 * @version		1.1.1
 * @package		Read More, Basic
 * @copyright	2009 Rockford Solutions, Inc. All rights reserved.
 * @license		GNU/GPL
 */

jimport('joomla.application.component.model');

/**
 * Email Model
 *
 * @package		Read More, Basic
 */
class ReadmoreModelEmail extends JModel {
	/**
	 * Database record id
	 *
	 * @access	protected
	 * @var		int
	 */
	protected $_id = 0;
	
	/**
	 * Database record data
	 *
	 * @access	protected
	 * @var		object
	 */
	protected $_data = null;
	
	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();
	}
	
	/**
	 * Sets record id and initializes record data
	 *
	 * @param	int		database record id
	 */
	public function setId($id) {
		$this->_id = (int) $id;
		$this->_data = null;
	}
	
	/**
	 * Builds a database query based on selected record id
	 *
	 * @return	string	database query
	 */
	protected function _buildQuery() {
		$query = 'SELECT * FROM #__readmore_email WHERE id = ' . $this->_id;
		
		return $query;
	}
	
	/**
	 * Returns database record data, performing database query if necessary
	 *
	 * @return	object	Record data
	 */
	public function &getData() {
		if (empty($this->_data)) {
			$query = $this->_buildQuery();
			
			$this->_db->setQuery($query);
			$this->_data = $this->_db->loadObject();
		}
		
		return $this->_data;
	}
	
	/**
	 * Inserts/Updates database record
	 *
	 * @param	string	Email address
	 * @return	bool	Record id on success, FALSE on failure
	 */
	public function store($email) {
		// Collect additional environment data
		$data = array();
		$data['email'] = $email;
		$data['addr'] = $_SERVER['REMOTE_ADDR'];
		$data['updated'] = date('Y-m-d H:i:s');
		$data['created'] = empty($data['id']) ? $data['updated'] : null;

		$row = &$this->getTable();
		
		// Bind data to record
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		// Check data for errors
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		// Insert/Update record
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		return $row->id;
	}
	
	/**
	 * Deletes database record
	 *
	 * @return	bool	TRUE on success, FALSE on failure
	 */
	public function delete() {
		$id = JRequest::getVar('id', 0);

		$row = &$this->getTable();
		
		if (!$row->delete($id)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return true;
	}
}
