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

defined('_JEXEC') or die;

use Joomla\CMS\Table\Table;

class TableRSForm_Google_Sheets extends Table
{
	public $form_id = null;

	public $gds_published = 0;
	public $gds_debug = 0;
	public $gds_spreadsheet_id = '';
	public $gds_sheet_id = '';
	public $gds_mappings = '';
	public $gds_trigger_on_payment = 0;

	/**
	 * Constructor
	 *
	 * @param object Database connector object
	 */
	public function __construct(& $db)
	{
		parent::__construct('#__rsform_google_sheets', 'form_id', $db);
	}
	
	public function check()
	{
		$this->gds_spreadsheet_id = trim($this->gds_spreadsheet_id);

		// process the Spreadsheet ID if an Google Sheet URL is given, else leave it as it is
		if (preg_match('/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/', $this->gds_spreadsheet_id, $matches))
		{
			$this->gds_spreadsheet_id = $matches[1];
		}

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

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