<?php
/**
 * @package    RSForm! Pro
 * @copyright  (c) 2007 - 2017 RSJoomla!
 * @link       https://www.rsjoomla.com
 * @license    GNU General Public License http://www.gnu.org/licenses/gpl-3.0.en.html
 */

defined('_JEXEC') or die('Restricted access');

class TableRSForm_2Checkout extends JTable
{
	/**
	 * Primary Key
	 *
	 * @var int
	 */
	public $form_id = null;
	public $vars;

	/**
	 * Constructor
	 *
	 * @param object Database connector object
	 */
	public function __construct(& $db)
	{
		parent::__construct('#__rsform_2checkout', 'form_id', $db);
	}

	public function bind($array, $ignore = '')
	{
		if (array_key_exists('vars', $array) && is_array($array['vars']))
		{
			$array['vars'] = json_encode($array['vars']);
		}

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

	public function load($keys = null, $reset = true)
	{
		$result = parent::load($keys, $reset);
		if ($result)
		{
			if ($this->vars)
			{
				$this->vars = json_decode($this->vars, true);
			}
			else
			{
				$this->vars = array();
			}
		}

		return $result;
	}

	// Validate data before save
	public function check()
	{
		if (is_array($this->vars))
		{
			$this->vars = json_encode($this->vars);
		}

		return true;
	}

	public function hasPrimaryKey()
	{
		$db 	= $this->getDbo();
		$key 	= $this->getKeyName();
		$table	= $this->getTableName();

		$query = $db->getQuery(true)
			->select($db->qn($key))
			->from($db->qn($table))
			->where($db->qn($key) . ' = ' . $db->q($this->{$key}));

		return $db->setQuery($query)->loadResult() !== null;
	}
}