<?php
/**
* @package RSForm!Pro
* @copyright (C) 2007-2019 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// no direct access
defined('_JEXEC') or die;

use Joomla\CMS\Table\Table;

class TableRSForm_Akismet extends Table
{
	public $form_id 		= null;
	public $aki_merge_vars 	= array();
	public $aki_published 	= 0;
	
	public function __construct(& $db)
	{
		parent::__construct('#__rsform_akismet', 'form_id', $db);
	}

	public function migrateData()
	{
		if (!empty($this->aki_merge_vars))
		{
			if (is_string($this->aki_merge_vars))
			{
				$this->aki_merge_vars = @unserialize($this->aki_merge_vars);

				if ($this->aki_merge_vars === false)
				{
					$this->aki_merge_vars = array();
				}
			}

			// Let's see if we have legacy values
			$vars = array(
				'author' 	=> 'comment_author',
				'email' 	=> 'comment_author_email',
				'website' 	=> 'comment_author_url',
				'body'		=> 'comment_content',
			);

			foreach ($vars as $oldVar => $newVar)
			{
				if (isset($this->aki_merge_vars[$oldVar]))
				{
					$this->aki_merge_vars[$newVar] = $this->aki_merge_vars[$oldVar];

					unset($this->aki_merge_vars[$oldVar]);
				}
			}
		}
	}

	// Validate data before save
	public function check()
	{
		$this->migrateData();

		if (is_array($this->aki_merge_vars))
		{
			$this->aki_merge_vars = serialize($this->aki_merge_vars);
		}

		return true;
	}

	public function load($keys = null, $reset = true)
	{
		$result = parent::load($keys, $reset);

		if ($result)
		{
			$this->aki_merge_vars = @unserialize($this->aki_merge_vars);

			if ($this->aki_merge_vars === false)
			{
				$this->aki_merge_vars = array();
			}
		}

		return $result;
	}

	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;
	}
}