<?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\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\Utilities\IpHelper;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Form\Form;

/**
 * RSForm! Pro system plugin
 */
class plgSystemRsfpdotmailer extends CMSPlugin
{
	protected $autoloadLanguage = true;

	public function onRsformFormSave($form)
	{
		$app			 = Factory::getApplication();
		$data 			 = $app->input->get('dotmailer', array(), 'array');
		$data['form_id'] = $app->input->getInt('formId',0);
		$row 			 = $this->getTable();

		if (!$row)
		{
			return false;
		}

		if (!$row->bind($data))
		{
			return false;
		}

		$row->check();

		if (!$row->store())
		{
			$app->enqueueMessage($row->getError(), 'error');
		}
	}

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

	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 onRsformBackendAfterShowFormEditTabs()
	{
		$app	= Factory::getApplication();
		$formId = $app->input->getInt('formId',0);
		$row	= $this->getTable();
		
		if (!$row) {
			return;
		}
		
		$row->load($formId);
		$row->dm_merge_vars = @unserialize($row->dm_merge_vars);
		if ($row->dm_merge_vars === false) {
			$row->dm_merge_vars = array();
		}
		
		require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/dotmailerapi.php';
		$dotmailer = new RSFPDotmailer();
		
		// Fields
		$fields_array = $this->_getFields($formId);
		$fields = array();
		foreach ($fields_array as $field)
			$fields[] = HTMLHelper::_('select.option', $field, $field);
		
		// Action
		$dotmailer_action = array(
			HTMLHelper::_('select.option', 1, Text::_('RSFP_DOTMAILER_ACTION_SUBSCRIBE')),
			HTMLHelper::_('select.option', 0, Text::_('RSFP_DOTMAILER_ACTION_UNSUBSCRIBE')),
			HTMLHelper::_('select.option', 3, Text::_('RSFP_DOTMAILER_ACTION_REMOVE')),
			HTMLHelper::_('select.option', 2, Text::_('RSFP_DOTMAILER_LET_USER_DECIDE'))
		);
		$lists['dm_action'] = HTMLHelper::_('select.genericlist', $dotmailer_action, 'dotmailer[dm_action]', 'onchange="dmChangeAction(this.value);"', 'value', 'text', $row->dm_action);
		
		// Action Field
		$lists['dm_action_field'] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_action_field]', $row->dm_action != 2 ? 'disabled="disabled"' : '', 'value', 'text', $row->dm_action_field);
		
		// OptIn Type
		$dotmailer_optin_type = array(
			HTMLHelper::_('select.option', 'Unknown', Text::_('RSFP_DOTMAILER_UNKNOWN')),
			HTMLHelper::_('select.option', 'Single', Text::_('RSFP_DOTMAILER_SINGLE')),
			HTMLHelper::_('select.option', 'VerifiedDouble', Text::_('RSFP_DOTMAILER_VERIFIEDDOUBLE')),
			HTMLHelper::_('select.option', 'user', Text::_('RSFP_DOTMAILER_LET_USER_DECIDE'))
		);
		$lists['dm_optin_type'] = HTMLHelper::_('select.genericlist', $dotmailer_optin_type, 'dotmailer[dm_optin_type]', 'onchange="dmChangeOptinType(this.value);"', 'value', 'text', $row->dm_optin_type);
		
		// OptIn Type Field
		$lists['dm_optin_type_field'] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_optin_type_field]', $row->dm_optin_type != 'user' ? 'disabled="disabled"' : '', 'value', 'text', $row->dm_optin_type_field);
		
		// Email Type
		$dotmailer_email_type = array(
			HTMLHelper::_('select.option', 'Html', Text::_('RSFP_DOTMAILER_HTML')),
			HTMLHelper::_('select.option', 'PlainText', Text::_('RSFP_DOTMAILER_TEXT')),
			HTMLHelper::_('select.option', 'user', Text::_('RSFP_DOTMAILER_LET_USER_DECIDE'))
		);
		$lists['dm_email_type'] = HTMLHelper::_('select.genericlist', $dotmailer_email_type, 'dotmailer[dm_email_type]', 'onchange="dmChangeEmailType(this.value);"', 'value', 'text', $row->dm_email_type);
		
		// Email Type Field
		$lists['dm_email_type_field'] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_email_type_field]', $row->dm_email_type != 'user' ? 'disabled="disabled"' : '', 'value', 'text', $row->dm_email_type_field);
		
		// DotMailer Lists
		try
		{
			$results = $dotmailer->getLists();
		}
		catch (Exception $e)
		{
			$app->enqueueMessage($e->getMessage(), 'error');
		}
		$dotmailer_lists = array(
			HTMLHelper::_('select.option', '', Text::_('RSFP_PLEASE_SELECT_LIST'))
		);
		
		if (!empty($results) && is_array($results))
		{
			foreach ($results as $result)
			{
				$dotmailer_lists[] = HTMLHelper::_('select.option', $result->id, $result->name);
			}
		}
		
		$lists['dm_list_id'] = HTMLHelper::_('select.genericlist', $dotmailer_lists, 'dotmailer[dm_list_id]', '', 'value', 'text', $row->dm_list_id);
		
		// Merge Vars
		$merge_vars = array();
		try
		{
			$merge_vars = $dotmailer->getFields();
		} catch (Exception $e)
		{
			$app->enqueueMessage($e->getMessage(), 'error');
		}
		
		$lists['dm_fields'] = array();
		if (is_array($merge_vars))
		{
			foreach ($merge_vars as $i => $merge_var)
			{
				$lists['dm_fields'][$merge_var->name] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_merge_vars]['.$merge_var->name.']', null, 'value', 'text', isset($row->dm_merge_vars[$merge_var->name]) ? $row->dm_merge_vars[$merge_var->name] : null);
			}
		}

		$lists['dm_email'] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_email]', '', 'value', 'text', $row->dm_email);
		$lists['dm_consent_field'] = HTMLHelper::_('select.genericlist', $fields, 'dotmailer[dm_consent_field]', '', 'value', 'text', $row->dm_consent_field);
		$lists['dm_published'] = RSFormProHelper::renderHTML('select.booleanlist','dotmailer[dm_published]','',$row->dm_published);

		Factory::getDocument()->addScriptDeclaration("function dmChangeAction(value) {
	document.getElementById('dotmailerdm_action_field').disabled = value !== '2';
}

function dmChangeOptinType(value) {
	document.getElementById('dotmailerdm_optin_type_field').disabled = value !== 'user';
}

function dmChangeEmailType(value) {
	document.getElementById('dotmailerdm_email_type_field').disabled = value !== 'user';
}");
		?>
		<div id="dotmailerdiv">
			<div class="alert alert-info"><?php echo Text::_('RSFP_DOTMAILER_DESC'); ?></div>
			<table class="table table-bordered">
				<tr>
					<td><?php echo Text::_('RSFP_DOTMAILER_USE_INTEGRATION'); ?></td>
					<td><?php echo $lists['dm_published']; ?></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip" title="<?php echo Text::_('RSFP_DOTMAILER_ACTION_DESC'); ?>"><?php echo Text::_('RSFP_DOTMAILER_ACTION'); ?></span>
					</td>
					<td><?php echo $lists['dm_action']; ?> <?php echo $lists['dm_action_field']; ?>
					<p><?php echo Text::_('RSFP_DOTMAILER_ACTION_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td><?php echo Text::_('RSFP_DOTMAILER_LIST_ID'); ?></td>
					<td><?php echo $lists['dm_list_id']; ?>
					<p><?php echo Text::_('RSFP_DOTMAILER_LIST_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip" title="<?php echo Text::_('RSFP_DOTMAILER_OPTIN_TYPE_DESC'); ?>"><?php echo Text::_('RSFP_DOTMAILER_OPTIN_TYPE'); ?></span>
					</td>
					<td><?php echo $lists['dm_optin_type']; ?> <?php echo $lists['dm_optin_type_field']; ?>
					<p><?php echo Text::_('RSFP_DOTMAILER_OPTIN_TYPE_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip" title="<?php echo Text::_('RSFP_DOTMAILER_EMAIL_TYPE_DESC'); ?>"><?php echo Text::_('RSFP_DOTMAILER_EMAIL_TYPE'); ?></span>
					</td>
					<td><?php echo $lists['dm_email_type']; ?> <?php echo $lists['dm_email_type_field']; ?>
						<p><?php echo Text::_('RSFP_DOTMAILER_EMAIL_TYPE_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip" title="<?php echo Text::_('RSFP_DOTMAILER_EMAIL_DESC'); ?>"><?php echo Text::_('RSFP_DOTMAILER_EMAIL'); ?></span>
					</td>
					<td><?php echo $lists['dm_email']; ?></td>
				</tr>
				<tr>
					<td>
						<span class="hasTip" title="<?php echo Text::_('RSFP_DOTMAILER_CONSENT_FIELD_DESC'); ?>"><?php echo Text::_('RSFP_DOTMAILER_CONSENT_FIELD'); ?></span>
					</td>
					<td><?php echo $lists['dm_consent_field']; ?></td>
				</tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_DOTMAILER_MERGE_VARS'); ?></h3>
			<p><?php echo Text::_('RSFP_DOTMAILER_MERGE_VARS_DESC'); ?></p>
			<table class="table table-bordered">
				<?php
				if (is_array($merge_vars))
				{
					foreach ($merge_vars as $merge_var)
					{
						?>
						<tr>
							<td><?php echo $merge_var->name; ?></td>
							<td><?php echo $lists['dm_fields'][$merge_var->name]; ?></td>
						</tr>
					<?php
					}
				}
				?>
			</table>
		</div>
		<?php
	}
	
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		echo '<li><a href="javascript: void(0);" id="dotmailer"><span class="rsficon rsficon-dot-circle-o"></span><span class="inner-text">'.Text::_('RSFP_DOTMAILER_INTEGRATION').'</span></a></li>';
	}
	
	public function onRsformFrontendBeforeStoreSubmissions($args)
	{
		$app	= Factory::getApplication();
		$formId	= (int) $args['formId'];
		$row	= $this->getTable();

		if ($row && $row->load($formId))
		{
			if (!$row->dm_published || !$row->dm_list_id || !$row->dm_email)
			{
				return;
			}
			
			require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/dotmailerapi.php';
			$dotmailer = new RSFPDotmailer();
			
			$row->dm_merge_vars = @unserialize($row->dm_merge_vars);
			if ($row->dm_merge_vars === false)
				$row->dm_merge_vars = array();
			
			$form =& $args['post'];
			
			$email_address = isset($form[$row->dm_email]) ? trim($form[$row->dm_email]) : '';
			
			$merge_vars = array();		
			if (!empty($row->dm_merge_vars))
			{
				foreach ($row->dm_merge_vars as $tag => $field)
				{
					if ($field == '- IGNORE -') continue;
					
					if (!isset($form[$field]))
						$form[$field] = '';
					
					if (is_array($form[$field]))
					{
						array_walk($form[$field], array($this, '_escapeCommas'));
						$form[$field] = implode(',', $form[$field]);
					}
					
					$merge_vars[] = array('Key' => $tag, 'Value' => $form[$field]);
				}
			}
			
			// OptIn Type
			$optin_type = $row->dm_optin_type;
			$valid_optin = array('Unknown', 'Single', 'VerifiedDouble');
			if ($row->dm_optin_type == 'user')
			{
				$optin_type = isset($form[$row->dm_optin_type_field]) && in_array(trim($form[$row->dm_optin_type_field]), $valid_optin) ? $form[$row->dm_optin_type_field] : 'Single';
			}
			
			// Email Type
			$email_type = $row->dm_email_type;
			$valid_email = array('Html', 'PlainText');
			if ($row->dm_email_type == 'user')
			{
				$email_type = isset($form[$row->dm_email_type_field]) && in_array(trim($form[$row->dm_email_type_field]), $valid_email) ? $form[$row->dm_email_type_field] : 'Html';
			}

			$list_id = $row->dm_list_id;
			
			// Subscribe action - Subscribe, Unsubscribe, Remove or Let the user choose
			$action = 'ignore';
			if ($row->dm_action == 0) {
				$action = 'unsubscribe';
			} elseif ($row->dm_action == 1) {
				$action = 'subscribe';
			} elseif ($row->dm_action == 3) {
				$action = 'remove';
			} elseif ($row->dm_action == 2 && isset($form[$row->dm_action_field])) {
				if (is_array($form[$row->dm_action_field])) {
					foreach ($form[$row->dm_action_field] as $i => $value) {
						$value = strtolower(trim($value));
						if ($value == 'subscribe') {
							$action = 'subscribe';
							break;
						} elseif ($value == 'unsubscribe') {
							$action = 'unsubscribe';
							break;
						} elseif ($value == 'remove') {
							$action = 'remove';
							break;
						}
					}
				} else {
					$form[$row->dm_action_field] = strtolower(trim($form[$row->dm_action_field]));
					if ($form[$row->dm_action_field] == 'subscribe') {
						$action = 'subscribe';
					} elseif ($form[$row->dm_action_field] == 'unsubscribe') {
						$action = 'unsubscribe';
					} elseif ($form[$row->dm_action_field] == 'remove') {
						$action = 'remove';
					}
				}
			}
			
			
			try {
				if ($action == 'subscribe')
				{
					$consentField = '';
					if (isset($form[$row->dm_consent_field]))
					{
						if (is_array($form[$row->dm_consent_field]))
						{
							$consentField = implode('', $form[$row->dm_consent_field]);
						}
						else
						{
							$consentField = $form[$row->dm_consent_field];
						}
					}

					$contact = array(
						'email' => $email_address,
						'optInType' => $optin_type,
						'emailType' => $email_type,
						'dataFields' => $merge_vars,
						'status' => 'Subscribed'
					);

					// Add new contact to list
					$result = $dotmailer->addContact($list_id, $contact);

					if ($consentField && $result)
					{
						$consentFields = array(
							array(
								'key' 	=> 'TEXT',
								'value' => $consentField
							),
							array(
								'key' 	=> 'DATETIMECONSENTED',
								'value' => Factory::getDate()->format('Y-m-d\TH:i:s.v\Z')
							),
							array(
								'key' 	=> 'URL',
								'value' => Uri::getInstance()->toString()
							),
							array(
								'key' 	=> 'IPADDRESS',
								'value' => IpHelper::getIp()
							),
							array(
								'key' 	=> 'USERAGENT',
								'value' => $app->input->server->get('HTTP_USER_AGENT', '', 'raw')
							)
						);

						$data = array(
							'contact' => $contact,
							'consentFields' => array(array('fields' => $consentFields))
						);

						$dotmailer->updateConsent($result->id, $data);
					}
				}
				elseif ($action == 'unsubscribe')
				{
					// Unsubscribe the user
					$contact = array(
						'email' => $email_address,
						'status' => 'Unsubscribed'
					);
					$dotmailer->unsubscribeContact($list_id, $contact);
				}
				elseif ($action == 'remove')
				{
					$dotmailer->removeContact($list_id,$email_address);
				}
			}
			catch (Exception $e)
			{
				$app->enqueueMessage($e->getMessage(), 'error');
			}
		}
	}
	
	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('PLG_SYSTEM_RSFPDOTMAILER_NAME'), 'form-dotmailer');
		$tabs->addContent($this->configurationScreen());
	}
	
	public function configurationScreen()
	{
		ob_start();

		Form::addFormPath(__DIR__ . '/forms');

		$form = Form::getInstance( 'plg_system_rsfpdotmailer.configuration', 'configuration', array('control' => 'rsformConfig'), false, false );
		$form->bind($this->loadFormData());

		?>
		<div id="page-dotmailer" class="form-horizontal">
			<?php
			foreach ($form->getFieldsets() as $fieldset)
			{
				if ($fields = $form->getFieldset($fieldset->name))
				{
					foreach ($fields as $field)
					{
						echo $field->renderField();
					}
				}
			}
			?>
		</div>
		<?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('dotmailer.%', false));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}
	
	public 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'));
		$fields = $db->setQuery($query)->loadColumn();
		
		array_unshift($fields, '- IGNORE -');
		return $fields;
	}
	
	protected function _escapeCommas(&$item) {
		$item = str_replace(',', '\,', $item);
	}

	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('dotmailer');
				foreach ($data as $property => $value)
				{
					$xml->add($property, $value);
				}
				$xml->add('/dotmailer');
			}
		}
	}
	
	public function onRsformFormRestore($form, $xml, $fields)
	{
		if (isset($xml->dotmailer))
		{
			$data = array(
				'form_id' => $form->FormId
			);
			
			foreach ($xml->dotmailer->children() as $property => $value)
			{
				$data[$property] = (string) $value;
			}
			
			$row = $this->getTable();
			$row->save($data);
		}
	}
	
	public function onRsformBackendFormRestoreTruncate() {
		Factory::getDbo()->truncateTable('#__rsform_dotmailer');
	}
}