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

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

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Form\Form;

if (!file_exists(JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/Ctct/constantcontact.php')) {
	return;
}

require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/Ctct/constantcontact.php';

class plgSystemRsfpconstantcontact extends CMSPlugin
{
	protected $autoloadLanguage = true;

	protected function getTable()
	{
		return Table::getInstance('RSForm_ConstantContact', 'Table');
	}

	public function onRsformFormSave($form)
	{
		$data 			 = Factory::getApplication()->input->get('ccontact', array(), 'array');
		$data['form_id'] = Factory::getApplication()->input->getInt('formId',0);
		$row 			 = $this->getTable();
		
		if (!$row)
		{
			return false;
		}
		
		return $row->save($data);
	}
	
	public function onRsformBackendFormCopy($args)
	{
		$formId = $args['formId'];
		$newFormId = $args['newFormId'];

		if ($row = $this->getTable())
		{
			if ($row->load($formId))
			{
				$row->form_id = $newFormId;

				$row->check();

				return $row->store();
			}
		}
	}

	public function onRsformBackendSwitchTasks() {
		$app = Factory::getApplication();
		$input = $app->input;
		$plugin_task = $input->getCmd('plugin_task','');
		
		switch ($plugin_task)
		{
			case 'deauth_cc':
				$config = RSFormProConfig::getInstance();

				$version = $config->get('cc_apiversion');
				
				if ($version == 'v3')
				{
					// Reset Access Token
					$config->set('cc.accesstoken', '');
				}

				$app->redirect(Uri::root().'administrator/index.php?option=com_rsform&view=configuration');
			break;
			case 'store_cc_access_token':
				try
				{
					$cc = new RSFormProConstantContact('v3');
					$client = $cc->getClient();
					if ($client->acquireAccessToken($_GET))
					{
						// store the new access token
						$cc->storeAccessToken($client->accessToken, $client->refreshToken, $client->expiresIn);

						$app->enqueueMessage('ConstantContact: '.Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACCESS_TOKEN_SUCCESSFUL'), 'success');
					}
					else
					{
						$error = 'Code: '.$client->getStatusCode().', error: '.$client->getLastError();
						throw new Exception($error);
					}
					
					
				}
				catch (Exception $e)
				{
					Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
				}
				
				
				$app->redirect(Uri::root().'administrator/index.php?option=com_rsform&view=configuration');
			break;

			case 'renew_cc_access_token':
				try
				{
					$cc = new RSFormProConstantContact('v3');
					
					// force the refresh token
					$cc->getToken(true);
					
					$app->enqueueMessage('ConstantContact: '.Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_RENEW_TOKEN_SUCCESSFUL'), 'success');
					
				}
				catch (Exception $e)
				{
					Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
				}
				
				
				$app->redirect(Uri::root().'administrator/index.php?option=com_rsform&view=configuration');
			break;

			case 'redirect_cc':
				// check to see if the api and secret are defined
				$api_key = RSFormProHelper::getConfig('cc.apiv3');
				$secret = RSFormProHelper::getConfig('cc.secret');

				if (!$api_key || !$secret)
				{
					Factory::getApplication()->enqueueMessage('ConstantContact: ' . Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_NEED_CLIENT_AND_SECRET'), 'warning');
					$app->redirect(Uri::root().'administrator/index.php?option=com_rsform&view=configuration');
				}

				try
				{
					$cc = new RSFormProConstantContact('v3');
					$client = $cc->getClient();

					$redirect_link = $client->getAuthorizationURL();
					
					$app->redirect($redirect_link);
				}
				catch (Exception $e)
				{
					Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
					$app->redirect(Uri::root().'administrator/index.php?option=com_rsform&view=configuration');
				}
			break;	
		}
	}
	
	public function onRsformBackendAfterShowFormEditTabs()
	{
		$formId = Factory::getApplication()->input->getInt('formId',0);
		$row	= $this->getTable();
		$fields = array();
		
		if (!$row) {
			return;
		}
		
		$row->load($formId);
		$row->cc_merge_vars = @unserialize($row->cc_merge_vars);
		if ($row->cc_merge_vars === false) {
			$row->cc_merge_vars = array();
		}
		
		$cc_action = array(
			HTMLHelper::_('select.option', 1, Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACTION_SUBSCRIBE')),
			HTMLHelper::_('select.option', 0, Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACTION_UNSUBSCRIBE')),
			HTMLHelper::_('select.option', 2, Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_LET_USER_DECIDE'))
		);
		
		$fields_array = $this->_getFields($formId);
		$fields[] = HTMLHelper::_('select.option', '', Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_IGNORE'));
		foreach ($fields_array as $field) {
			$fields[] = HTMLHelper::_('select.option', $field, $field);
		}

		// set the cc object
		$version = RSFormProHelper::getConfig('cc_apiversion');
		try
		{
			$cc = new RSFormProConstantContact($version);
		}
		catch (Exception $e)
		{
			Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
		}

		// initalise the vars
		$merge_vars = [];

		try {
			if ($cc->getStatus())
			{
				$cc->setMergeFields();
				$merge_vars = $cc->getMergeFields();
			}
			else
			{
				$error = $cc->getLastError();
				// only show when the integration is used
				if ($row->cc_published && strlen($error))
				{
					Factory::getApplication()->enqueueMessage('ConstantContact: '.$error, 'warning');
				}
			}
		}
		catch (Exception $e)
		{
			Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
		}
		
		// Show system messages
		$lists['cc_show_messages'] = RSFormProHelper::renderHTML('select.booleanlist','ccontact[cc_show_messages]', '', is_null($row->cc_show_messages) ? 0 : $row->cc_show_messages);
		
		// Enable integration
		$lists['cc_published'] = RSFormProHelper::renderHTML('select.booleanlist','ccontact[cc_published]', '', is_null($row->cc_published) ? 0 : $row->cc_published);
		
		// Action
		$lists['cc_action'] = HTMLHelper::_('select.genericlist', $cc_action, 'ccontact[cc_action]', 'class="form-select" onchange="ccChangeAction(this.value);"', 'value', 'text', $row->cc_action);
		
		// Action field
		$lists['cc_action_field'] = HTMLHelper::_('select.genericlist', $fields, 'ccontact[cc_action_field]', 'class="form-select mt-2"'.($row->cc_action != 2 ? 'disabled="disabled"' : ''), 'value', 'text', $row->cc_action_field);
		
		// Delete
		$lists['cc_delete_member'] = RSFormProHelper::renderHTML('select.booleanlist','ccontact[cc_delete_member]','', is_null($row->cc_delete_member) ? 0 : $row->cc_delete_member);
		
		// Lists
		$lists['cc_list_id'] = HTMLHelper::_('select.genericlist', $this->getLists($row->cc_published), 'ccontact[cc_list_id]', 'class="form-select" onchange="ccShowVars(this.value)"', 'value', 'text', $row->cc_list_id);
		
		// Update existing contact
		$lists['cc_update'] = RSFormProHelper::renderHTML('select.booleanlist','ccontact[cc_update]','', is_null($row->cc_update) ? 0 : $row->cc_update);
		
		// Fields
		$lists['cc_fields'] = array();
		if (is_array($merge_vars)) {
			foreach ($merge_vars as $merge_var => $title) {
				$lists['cc_fields'][$merge_var] = HTMLHelper::_('select.genericlist', $fields, 'ccontact[cc_merge_vars]['.$merge_var.']', 'class="form-select"', 'value', 'text', isset($row->cc_merge_vars[$merge_var]) ? $row->cc_merge_vars[$merge_var] : null);
			}
		}

		Factory::getDocument()->addScriptDeclaration("
function ccShowVars(val) {
	document.getElementById('merge_vars_cc').style.display = val === '0' ? 'none' : '';
}

function ccChangeAction(value) {
	document.getElementById('ccontactcc_action_field').disabled = value !== '2';
}

window.addEventListener('DOMContentLoaded', function() {
	ccShowVars(document.getElementById('ccontactcc_list_id').value);
});");
		?>
		<div id="constantcontactdiv">
			<h3 class="rsfp-legend"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_NAME'); ?></h3>
			<div class="alert alert-info"><?php echo Text::_('RSFP_CONSTANTCONTACT_DESC'); ?></div>
			<table class="table table-bordered">
				<tr>
					<td><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_USE_INTEGRATION'); ?></td>
					<td><?php echo $lists['cc_published']; ?></td>
				</tr>
				<tr>
					<td><span class="hasTip hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_SHOW_SYSTEM_MESSAGES_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_SHOW_SYSTEM_MESSAGES'); ?></span></td>
					<td><?php echo $lists['cc_show_messages']; ?></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACTION_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACTION'); ?></span>
					</td>
					<td><?php echo $lists['cc_action']; ?> <?php echo $lists['cc_action_field']; ?>
					<p><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_ACTION_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_LIST_ID'); ?></td>
					<td><?php echo $lists['cc_list_id']; ?></td>
				</tr>
				<tr>
					<td><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_UPDATE_CONTACT'); ?></td>
					<td><?php echo $lists['cc_update']; ?></td>
				</tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_UNSUBSCRIBE_OPTIONS'); ?></h3>
			<table class="table table-bordered">
				<tr>
					<td>
						<span class="hasTip hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DELETE_MEMBER_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DELETE_MEMBER'); ?></span>
					</td>
					<td><?php echo $lists['cc_delete_member']; ?></td>
				</tr>
			</table>

			<div id="merge_vars_cc">
				<h3 class="rsfp-legend"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_MERGE_VARS'); ?></h3>
				<p><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_MERGE_VARS_DESC'); ?></p>
				<table class="table table-bordered">
					<tbody>
					<?php if (is_array($merge_vars)) { ?>
						<?php foreach ($merge_vars as $merge_var => $title) { ?>
							<tr>
								<td><?php echo $title; ?></td>
								<td><?php echo $lists['cc_fields'][$merge_var]; ?></td>
							</tr>
						<?php } ?>
					<?php } ?>
					</tbody>
				</table>
			</div>
		</div>
		<?php
	}
	
	protected function getLists($use = null) {
		$version = RSFormProHelper::getConfig('cc_apiversion');
		
		$lists	= array(HTMLHelper::_('select.option', '0', Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_PLEASE_SELECT_LIST')));
		
		if (is_null($use))
		{
			return $lists;
		}

		try
		{
			$cc = new RSFormProConstantContact($version);
		}
		catch (Exception $e)
		{
			Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
			// return the current list
			return $lists;
		}

		// continue if the api data is set
		
		if ($cc->getStatus())
		{
			try 
			{
				if ($cclists = $cc->getLists()) 
				{
					foreach ($cclists as $cclist) {
						$lists[] = HTMLHelper::_('select.option', $cclist->id, $cclist->name);
					}
				}
			} catch (Exception $e)
			{
				Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
			}
		}
		else
		{
			$error = $cc->getLastError();
			// only show when the integration is used
			if ($use && strlen($error))
			{
				Factory::getApplication()->enqueueMessage('ConstantContact: '.$error, 'warning');
			}
		}
		
		return $lists;
	}
	
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		echo '<li><a href="javascript: void(0);" id="constantcontact"><span class="rsficon rsficon-envelope"></span><span class="inner-text">'.Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_INTEGRATION').'</span></a></li>';
	}
	
	public function onRsformFrontendAfterFormProcess($args)
	{
		$formId	= (int) $args['formId'];
		$row	= $this->getTable();

		if ($row && $row->load($formId))
		{
			if (!$row->cc_published || !$row->cc_list_id)
			{
				return;
			}
			
			$row->cc_merge_vars = @unserialize($row->cc_merge_vars);
			if ($row->cc_merge_vars === false) {
				$row->cc_merge_vars = array();
			}
			
			if (!isset($row->cc_merge_vars['email_address'])) {
				return;
			}
			
			$form	= Factory::getApplication()->input->get('form', array(), 'array');
			$email	= isset($form[$row->cc_merge_vars['email_address']]) ? $form[$row->cc_merge_vars['email_address']] : null;
			
			if (!$email) {
				return;
			}
			
			$subscribe = true;
			if ($row->cc_action == 1) {
				$subscribe = true;
			} elseif ($row->cc_action == 0) {
				$subscribe = false;
			} elseif ($row->cc_action == 2 && isset($form[$row->cc_action_field])) {
				$subscribe = null;
				if (is_array($form[$row->cc_action_field])) {
					foreach ($form[$row->cc_action_field] as $i => $value) {
						$value = strtolower(trim($value));
						if ($value == 'subscribe') {
							$subscribe = true;
							break;
						} elseif ($value == 'unsubscribe') {
							$subscribe = false;
							break;
						}
					}
				} else {
					$form[$row->cc_action_field] = strtolower(trim($form[$row->cc_action_field]));
					if ($form[$row->cc_action_field] == 'subscribe') {
						$subscribe = true;
					} elseif ($form[$row->cc_action_field] == 'unsubscribe') {
						$subscribe = false;
					} else {
						$subscribe = null;
					}
				}
			}
			
			$merge_vars = array();
			$merge_vars['addresses'][] = array();
			$merge_vars['notes'][] = array();
			
			foreach ($row->cc_merge_vars as $tag => $field) {
				if (empty($tag)) continue;
				if ($tag == 'email_address') continue;
				
				if (!isset($form[$field]))
					$form[$field] = '';
				
				if (is_array($form[$field]))
				{
					array_walk($form[$field], array($this, '_escapeCommas'));
					$form[$field] = implode(',', $form[$field]);
				}
				
				if (strncmp($tag, 'CustomField', strlen('CustomField')) === 0) {
					$merge_vars['custom_fields'][] = array('name' => $tag, 'value' => $form[$field]);
				} elseif (strncmp($tag, 'note', strlen('note')) === 0) {
					if (!empty($form[$field])) {
						$merge_vars['notes'][0][str_replace('note_','',$tag)] = $form[$field];
					}
				} elseif (strncmp($tag, 'address_', strlen('address_')) === 0) {
					$merge_vars['addresses'][0][substr($tag, strlen('address_'))] = $form[$field];
				} else {
					$merge_vars[$tag] = $form[$field];
				}
			}
			
			if (empty($merge_vars['notes'][0])) {
				unset($merge_vars['notes']);
			}
			
			$address_type = &$merge_vars['addresses'][0]['address_type'];
			
			if (empty($address_type) || !in_array($address_type, array('PERSONAL', 'BUSINESS'))) {
				$address_type = 'PERSONAL';
			}
			
			$version = RSFormProHelper::getConfig('cc_apiversion');
			try
			{
				$cc = new RSFormProConstantContact($version);
			}
			catch (Exception $e)
			{
				return;
			}

			// do not continue if the api data is not set
			if (!$cc->getStatus())
			{
				return;
			}
			
			if ($subscribe) {
				try {
					$response = $cc->getContactByEmail($email);
					
					// Add contact
					if (empty($response->results))
					{
						$cc->addContact($email, $row->cc_list_id, $merge_vars);
					} 
					else 
					{
						// Update contact
						if ($row->cc_update)
						{
							$cc->updateContact($email, $row->cc_list_id, $merge_vars);
						} 
						else
						{
							Factory::getApplication()->enqueueMessage(Text::sprintf('PLG_SYSTEM_RSFPCONSTANTCONTACT_EMAIL_COULD_NOT_UPDATE', $email), 'warning');
						}
					}
				} 
				catch (Exception $e)
				{
					if ($row->cc_show_messages)
					{
						Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
					}
				}
			} 
			elseif ($subscribe === false)
			{
				try 
				{
					$delete_member = $row->cc_delete_member ? true : false; // accepts only bool
					$cc->deleteContact($email, $delete_member, $row->cc_list_id);
					
				} 
				catch (Exception $e)
				{
					if ($row->cc_show_messages)
					{
						Factory::getApplication()->enqueueMessage('ConstantContact: '.$e->getMessage(), 'warning');
					}
				}
			}
		}
	}
	
	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_NAME'), 'form-constantcontact');
		$tabs->addContent($this->configurationScreen());
	}
	
	protected function configurationScreen()
	{
		ob_start();

		Form::addFormPath(__DIR__ . '/forms');
		
		Text::script('PLG_SYSTEM_RSFPCONSTANTCONTACT_ARE_YOU_SURE_DEAUTH');

		$form = Form::getInstance( 'plg_system_rsfpconstantcontact.configuration', 'configuration', array('control' => 'rsformConfig'), false, false );
		$form_data = $this->loadFormData();
		$form->bind($form_data);
		
		$is_token = $form_data['cc_apiversion'] == 'v3' && $form_data['cc.apiv3'] && $form_data['cc.accesstoken'];

		?>
		<div id="page-constantcontact" class="form-horizontal">
			<p class="rsfpccv2" style="display:none"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_API_KEY_REQUEST'); ?></p>
			<p class="rsfpccv3" style="display:none"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_API_KEY_REQUEST_V3'); ?></p>
			<?php
			foreach ($form->getFieldsets() as $fieldset)
			{
				if ($fields = $form->getFieldset($fieldset->name))
				{
					foreach ($fields as $field)
					{
						if ($is_token)
						{
							$field->disabled = true;
						}
						echo $field->renderField();
					}
				}
			}
			?>
		</div>
		
		<?php if (!$is_token) { ?>
		<div class="rsfpccv3" style="display:none">
			<div class="control-group">
				<div class="control-label">
					<label class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_REDIRECT_URI_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_REDIRECT_URI'); ?></label>
				</div>
				<div class="controls">
					<?php echo Uri::root().'administrator/index.php?option=com_rsform&task=plugin&plugin_task=store_cc_access_token'; ?>
					<p><small><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_REDIRECT_URI_DESC'); ?></small></p>
				</div>
			</div>
		</div>
		<?php } ?>
		
		<?php
		
		
		if ($form_data['cc.apiv3'] && $form_data['cc.secret'])
		{
			?>
			<div class="rsfpccv3" style="display:none">
			<?php
				try
				{
					$cc = new RSFormProConstantContact('v3');
					$status = $cc->getAccessTokenStatus();

					if (!$status->status)
					{
						switch($status->type)
						{
							case 'none':
								?>
									<div class="control-group">
										<div class="control-label">
											<label class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_GET_ACCESS_TOKEN_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_GET_ACCESS_TOKEN'); ?></label>
										</div>
										<div class="controls">
											<a href="<?php echo Uri::root().'administrator/index.php?option=com_rsform&task=plugin&plugin_task=redirect_cc'; ?>" class="btn btn-primary"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_AUTHENTICATE'); ?></a>
										</div>
									</div>
								<?php
							break;

							case 'is_expired':
								?>
									<div class="control-group">
										<div class="control-label">
											<label class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_RENEW_ACCESS_TOKEN_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_RENEW_ACCESS_TOKEN'); ?></label>
										</div>
										<div class="controls">
											<a href="<?php echo Uri::root().'administrator/index.php?option=com_rsform&task=plugin&plugin_task=renew_cc_access_token'; ?>" class="btn btn-success"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_RENEW'); ?></a>
										</div>
									</div>
								<?php
							break;	
						}
					}
					else
					{
						?>
							<div class="control-group">
								<div class="control-label">
									<label class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DEAUTHENTICATE_TASK_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DEAUTHENTICATE_TASK'); ?></label>
								</div>
								<div class="controls">
									<a onclick="return confirm(Joomla.JText._('PLG_SYSTEM_RSFPCONSTANTCONTACT_ARE_YOU_SURE_DEAUTH'));" href="<?php echo Uri::root().'administrator/index.php?option=com_rsform&task=plugin&plugin_task=deauth_cc'; ?>" class="btn btn-danger"><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DEAUTHENTICATE'); ?></a>
									<p><small><?php echo Text::_('PLG_SYSTEM_RSFPCONSTANTCONTACT_DEAUTHENTICATE_TASK_DESC'); ?></small></p>
								</div>
							</div>
						<?php
					}

					
				}
				catch (Exception $e)
				{
					$msg = $e->getMessage();
					echo '<div class="alert alert-info">'.$msg.'</div>';
				}
			?>
			</div>
			<?php
		}
		
		?>
		<script>
			document.addEventListener("DOMContentLoaded", () => {
				const rsfpccversion = document.getElementById('rsformConfig_cc_apiversion');
				// first time run
				rsfpccToggleVersion(rsfpccversion);
				
				rsfpccversion.addEventListener("change", (e) => {
					const element = e.currentTarget;
					
					if (element == rsfpccversion)
					{
						rsfpccToggleVersion(e.currentTarget);
					}
				});
			});
			
			function rsfpccToggleVersion(elem)
			{
				let current_value = elem.value;
				let v2_elements =  document.getElementsByClassName("rsfpccv2");
				let v3_elements =  document.getElementsByClassName("rsfpccv3");
				
				v2_elements = [...v2_elements];
				v3_elements = [...v3_elements];
	
				let visual_state_v2 = current_value == 'v3' ? 'none' : 'block';
				let visual_state_v3 = current_value == 'v3' ? 'block' : 'none';
				
				v3_elements.forEach(element => {
					element.style.display = visual_state_v3;
				});

				v2_elements.forEach(element => {
					element.style.display = visual_state_v2;
				});
				
			}
		</script>
		<?php

		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;
	}

	private function loadFormData()
	{
		$data 	= array();
		$db 	= Factory::getDbo();

		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn('#__rsform_config'))
			->where($db->qn('SettingName') . ' LIKE ' . $db->q('cc.%', false). ' OR '.$db->qn('SettingName').' = '.$db->q('cc_apiversion'));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}
	
	public function onRsformFormDelete($formId)
	{
		if ($row = $this->getTable())
		{
			$row->delete($formId);
		}
	}
	
	public function onRsformFormBackup($form, $xml, $fields)
	{
		if ($row = $this->getTable())
		{
			if ($row->load($form->FormId))
			{
				$row->check();

				$data = $row->getProperties();
				unset($data['form_id']);

				$xml->add('constantcontact');
				foreach ($data as $property => $value)
				{
					$xml->add($property, $value);
				}
				$xml->add('/constantcontact');
			}
		}
	}
	
	public function onRsformFormRestore($form, $xml, $fields)
	{
		if (isset($xml->constantcontact))
		{
			$data = array(
				'form_id' => $form->FormId
			);
			
			foreach ($xml->constantcontact->children() as $property => $value)
			{
				$data[$property] = (string) $value;
			}
			
			$row = $this->getTable();
			$row->save($data);
		}
	}
	
	public function onRsformBackendFormRestoreTruncate() {
		Factory::getDbo()->truncateTable('#__rsform_constantcontact');
	}
	
	protected function _getFields($formId)
	{
		$db    = Factory::getDbo();
		$query = $db->getQuery(true)
			->select($db->qn('p.PropertyValue'))
			->from($db->qn('#__rsform_components', 'c'))
			->join('LEFT', $db->qn('#__rsform_properties', 'p') . ' ON (' . $db->qn('c.ComponentId') . '=' . $db->qn('p.ComponentId') . ')')
			->where($db->qn('c.FormId') . '=' . $db->q($formId))
			->where($db->qn('p.PropertyName') . '=' . $db->q('NAME'))
			->order($db->qn('c.Order') . ' ' . $db->escape('ASC'));

		return $db->setQuery($query)->loadColumn();
	}
	
	protected function _escapeCommas(&$item) {
		$item = str_replace(',', '\,', $item);
	}
}