<?php
/**
 * @copyright	Copyright (c) 2015 Skyline Technology Ltd (http://extstore.com). All rights reserved.
 * @license		http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// No direct access.
defined('_JEXEC') or die;

/**
 * ExtStore Advanced Popup Component - Popup Table Class.
 *
 * @package		Joomla.Administrator
 * @subpakage	ExtStore.AdvPopup
 */
class AdvPopupTablePopup extends JTable {

	/**
	 * Constructor.
	 *
	 * @param	JDatabase	A database connector object.
	 */
	public function __construct(&$db) {
		parent::__construct('#__advpopup_popups', 'id', $db);
	}

	/**
	 * Overloaded bind function to pre-process the params.
	 *
	 * @param	array		Named array
	 * @return	null|string	null is operation was satisfactory, otherwise returns an error.
	 * @see		JTable:bind
	 */
	public function bind($array, $ignore = '') {
		if (isset($array['params']) && is_array($array['params'])) {
			$registry			= new JRegistry();
			$registry->loadArray($array['params']);
			$array['params']	= (string) $registry;
		}

		return parent::bind($array, $ignore);
	}

	/**
	 * Overload the store method for the Popup table.
	 *
	 * @param	boolean	Toggle whether null values should be updated.
	 * @return	boolean	True on success, false on failure.
	 */
	public function store($updateNulls = false) {
		$date	= JFactory::getDate();
		$user	= JFactory::getUser();

		if ($this->id) {
			// Existing item
			$this->modified		= $date->toSql();
			$this->modified_by	= $user->get('id');
		} else {
			// New Popup. A Popup created and created_by field can be set by the user,
			// so we don't touch either of these if they are set.
			if (! (int) $this->created) {
				$this->created	= $date->toSql();
			}

			if (empty($this->created_by)) {
				$this->created_by	= $user->get('id');
			}

		}


		// Attempt to store the user data.
		return parent::store($updateNulls);
	}

	/**
	 * Overloaded check method to ensure data integrity.
	 *
	 * @return	boolean		True on success.
	 */
	public function check() {
		// check for valid name
		if (trim($this->title) == '') {
			$this->setError(JText::_('COM_ADVPOPUP_POPUP_ERROR_TABLES_TITLE'));
			return false;
		}

		// check for existing name
		$query = 'SELECT id'
				. ' FROM #__advpopup_popups'
				. ' WHERE title = ' . $this->_db->quote($this->title)
		;
		$this->_db->setQuery($query);

		$xid	= intval($this->_db->loadResult());
		if ($xid && $xid != intval($this->id)) {
			$this->setError(JText::_('COM_ADVPOPUP_POPUP_ERROR_TABLES_NAME'));
			return false;
		}

		return true;
	}
}