<?php
/**
 * @package        RSForm! Pro
 * @copyright  (c) 2007 - 2020 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;

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

/**
 * Class plgSystemRsfpmailchimp
 */
class plgSystemRsfpmailchimp extends CMSPlugin
{
	/**
	 * @var bool
	 */
	protected $autoloadLanguage = true;

	protected $mailchimpData = array();

	/**
	 * Save the form properties
	 *
	 * @param $form
	 *
	 * @return bool|void
	 */
	public function onRsformFormSave($form)
	{
		$app          				= Factory::getApplication();
		$data 						= $app->input->post->get('mailchimp', array(), 'array');
		$data['form_id'] 			= $form->FormId;
		$data['mc_merge_vars'] 		= $app->input->post->get('merge_vars', array(), 'array');
		$data['mc_interest_groups']	= $app->input->post->get('interest_groups', array(), 'array');
		$data['mc_tags'] 			= $app->input->post->get('mc_tags', '', 'raw');
		$data['mc_cached_values'] 	= $app->input->post->get('mc_cached_values', array(), 'array');

		$row = $this->getTable();
		if (!$row)
		{
			return false;
		}

		try
		{
			if (!$row->bind($data))
			{
				throw new Exception (Text::_('COM_RSFP_MAILCHIMP_COULD_NOT_BIND_DATA'));
			}

			$row->check();

			if (!$row->store())
			{
				throw new Exception($row->getError());
			}

			return true;
		}
		catch (Exception $e)
		{
			$app->enqueueMessage($e->getMessage(), 'error');

			return false;
		}
	}

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

	/**
	 * Function that generates the Form Properties - Mailchimp tab content
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function onRsformBackendAfterShowFormEditTabs()
	{
		$formId = Factory::getApplication()->input->getInt('formId', 0);
		$row    = $this->getTable();

		if (!$row)
		{
			return false;
		}

		$row->load($formId, false);
		$row->mc_merge_vars = @unserialize($row->mc_merge_vars);

		if ($row->mc_merge_vars === false)
		{
			$row->mc_merge_vars = array();
		}

		$row->mc_interest_groups = @unserialize($row->mc_interest_groups);
		if ($row->mc_interest_groups === false)
		{
			$row->mc_interest_groups = array();
		}

		if (!RSFormProHelper::getConfig('mailchimp.key'))
		{
			?>
			<div id="mailchimpdiv">
				<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_NAME') ?></h3>
				<div class="alert alert-warning"><?php echo Text::_('RSFP_MAILCHIMP_NO_KEY_ADDED') ?></div>
			</div>
			<?php
			return;
		}

		require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/mcapi.php';
		$mailchimp = RSFormPro_Mailchimp::getInstance();

		// Fields
		$fields_array = $this->_getFields($formId);
		$fields       = array();
		foreach ($fields_array as $field)
		{
			$fields[] = HTMLHelper::_('select.option', $field, $field);
		}

		// Action
		$mailchimp_action   = array(
			HTMLHelper::_('select.option', 1, Text::_('RSFP_MAILCHIMP_ACTION_SUBSCRIBE')),
			HTMLHelper::_('select.option', 0, Text::_('RSFP_MAILCHIMP_ACTION_UNSUBSCRIBE')),
			HTMLHelper::_('select.option', 2, Text::_('RSFP_MAILCHIMP_LET_USER_DECIDE'))
		);
		$lists['mc_action'] = HTMLHelper::_('select.genericlist', $mailchimp_action, 'mailchimp[mc_action]', 'onchange="mcChangeAction(this.value);"', 'value', 'text', $row->mc_action);

		// Action Field
		$lists['mc_action_field'] = HTMLHelper::_('select.genericlist', $fields, 'mailchimp[mc_action_field]', $row->mc_action != 2 ? 'disabled="disabled"' : '', 'value', 'text', $row->mc_action_field);

		// Email Type
		$mailchimp_email_type   = array(
			HTMLHelper::_('select.option', 'html', Text::_('RSFP_MAILCHIMP_HTML')),
			HTMLHelper::_('select.option', 'text', Text::_('RSFP_MAILCHIMP_TEXT')),
			HTMLHelper::_('select.option', 'mobile', Text::_('RSFP_MAILCHIMP_MOBILE')),
			HTMLHelper::_('select.option', 'user', Text::_('RSFP_MAILCHIMP_LET_USER_DECIDE'))
		);
		$lists['mc_email_type'] = HTMLHelper::_('select.genericlist', $mailchimp_email_type, 'mailchimp[mc_email_type]', 'onchange="mcChangeEmailType(this.value);"', 'value', 'text', $row->mc_email_type);

		// Email Type Field
		$lists['mc_email_type_field'] = HTMLHelper::_('select.genericlist', $fields, 'mailchimp[mc_email_type_field]', $row->mc_email_type != 'user' ? 'disabled="disabled"' : '', 'value', 'text', $row->mc_email_type_field);

		// MailChimp Lists
		$results = $mailchimp->get_lists();

		$mailchimp_lists = array(
			HTMLHelper::_('select.option', '', Text::_('RSFP_PLEASE_SELECT_LIST'))
		);

		$lists['mc_list_id'] = '';
		if ($results)
		{
			foreach ($results as $result)
			{
				$mailchimp_lists[] = HTMLHelper::_('select.option', $result['id'], $result['name']);
			}
		}
		$lists['mc_list_id'] = HTMLHelper::_('select.genericlist', $mailchimp_lists, 'mailchimp[mc_list_id]', 'onchange="mcChangeList(this.value);"', 'value', 'text', $row->mc_list_id);

		// Merge Vars
		$merge_vars = Text::_('RSFP_PLEASE_SELECT_LIST');
		if ($row->mc_list_id)
		{
			$merge_vars = $mailchimp->get_merge_fields($row->mc_list_id);
		}
		
		$lists['fields'] = array();
		if (is_array($merge_vars))
		{
			foreach ($merge_vars as $merge_var)
			{
				$value = isset($row->mc_merge_vars[$merge_var->tag]) ? $row->mc_merge_vars[$merge_var->tag] : null;

				// handle address type field
				if ($merge_var->type == 'address') {
					if (!is_array($value)) {
						$array_values = array(
							'addr1' => (!empty($value) ? $value : ''), // if a field is already mapped add it to the addr1 field
							'addr2' => '',
							'city' => '',
							'state' => '',
							'zip' => '',
							'country' => ''
						);
					} else {
						$array_values = $value;
					}

					foreach ($array_values as $a_field => $a_value)
					{
						$lists['fields'][$merge_var->tag]['field'][$a_field]['field'] = '<input id="' . $merge_var->tag . '_' . $a_field . '" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" name="merge_vars[' . $merge_var->tag . '][' . $a_field . ']" value="' . $a_value . '" type="text">';

						if ($a_field == 'country') {
							$lists['fields'][$merge_var->tag]['field'][$a_field]['extra'] = Text::_('RSFP_MAILCHIMP_VARS_ARRAY_COUNTRY_DESC');
						}
					}

				} else {
					// handle the rest of the field types
					$lists['fields'][$merge_var->tag]['field'] = '<input id="' . $merge_var->tag . '" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" name="merge_vars[' . $merge_var->tag . ']" value="' . $value . '" type="text">';

					$extra = array();
					if ($merge_var->type == 'birthday') {
						$extra[] = Text::sprintf('RSFP_MAILCHIMP_BIRTHDAY_FIELD_FORMAT', $merge_var->options->date_format);
					}

					if (!empty($merge_var->options->choices)) {
						$extra[] = Text::_('RSFP_MAILCHIMP_CHOICES_AVAILABLE');
						foreach ($merge_var->options->choices as $choice) {
							$extra[] = $choice;
						}
					}

					if (!empty($extra)) {
						$extra = implode('<br/>', $extra);
						$lists['fields'][$merge_var->tag]['extra'] = $extra;
					}
				}
			}
		}

		// Interest Groups
		$interest_groups = Text::_('RSFP_PLEASE_SELECT_LIST');
		if ($row->mc_list_id)
		{
			$interest_groups = $mailchimp->get_interest_categories($row->mc_list_id);
		}

		$lists['fields_groups'] = array();
		if (is_array($interest_groups))
		{
			foreach ($interest_groups as $interest_group)
			{
				$lists['fields_groups'][$interest_group->id] = HTMLHelper::_('select.genericlist', $fields, 'interest_groups[' . $interest_group->title . ']', null, 'value', 'text', isset($row->mc_interest_groups[$interest_group->title]) ? $row->mc_interest_groups[$interest_group->title] : null);

				$lists['field_groups_desc'][$interest_group->id] = array();
				
				$interests = $mailchimp->get_interests($row->mc_list_id, $interest_group->id);
				$cached_values = array();
				if ($interests)
				{
					foreach ($interests as $group)
					{
						$lists['field_groups_desc'][$interest_group->id][] = $group->id . '|' . $group->name;
						$cached_values[$group->name] = $group->id;
					}
				}
				
				$lists['field_groups_desc'][$interest_group->id] = implode("\n", $lists['field_groups_desc'][$interest_group->id]);
				$lists['cached_values'][$interest_group->id] = '<input type="hidden" name="mc_cached_values['.htmlspecialchars($interest_group->title).']" value="'.htmlspecialchars(json_encode($cached_values)).'" />';
			}
		}

		// Tags
		$tags = Text::_('RSFP_PLEASE_SELECT_LIST');
		if ($row->mc_list_id)
		{
			$tags = $mailchimp->get_tags($row->mc_list_id);
		}

		$tag_lists = array();
		if (is_array($tags))
		{
			foreach ($tags as $tag)
			{
				$tag_lists[] = $tag->name;
			}
		}
		$lists['mc_double_optin']      		   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_double_optin]', '', $row->mc_double_optin);
		$lists['mc_update_existing']   		   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_update_existing]', ' onchange="mcToggleTagOptions(this.value)"', $row->mc_update_existing);
		$lists['mc_append_tags']   			   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_append_tags]', '', $row->mc_append_tags);
		$lists['mc_trigger_tags_automation']   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_trigger_tags_automation]', '', $row->mc_trigger_tags_automation);
		$lists['mc_replace_interests'] 		   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_replace_interests]', '', $row->mc_replace_interests);
		$lists['mc_delete_member'] 			   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_delete_member]', '', $row->mc_delete_member);
		$lists['published'] 				   = RSFormProHelper::renderHTML('select.booleanlist', 'mailchimp[mc_published]', '', $row->mc_published);

		Text::script('RSFP_MAILCHIMP_INTEREST_GROUP_DESC');
		Text::script('RSFP_MAILCHIMP_TAGS_AVAILABLE_DESC');

		Factory::getDocument()->addStyleDeclaration('#merge_vars input, #mc_tags { margin-bottom : 0; }');
		?>
		<div id="mailchimpdiv">
			<script type="text/javascript">
				function mcChangeList(value) {
					var params = {list_id: null},
						merge_vars = jQuery('#merge_vars'),
						interest_groups = jQuery('#interest_groups'),
						url = 'index.php?option=com_rsform&task=plugin&plugin_task=mailchimp.get_merge_vars';

					stateLoading();
					params.list_id = value;

					jQuery.ajax({
						type    : "POST",
						url     : url,
						data    : params,
						success : function (response) {
							stateDone();
							merge_vars.find("tr:gt(0)").remove();
							if (response.merge_vars.length) {
								jQuery.each(response.merge_vars, function () {
									if (this.type == 'address') {
										var that = this;
										jQuery.each(this.address_fields, function(field, f_tag) {
											var extra = '';
											if (typeof f_tag == 'object') {
												extra = f_tag.extra;
												f_tag = f_tag.label;
											}
											merge_vars.append('<tr><td>(' + that.tag + ') ' + that.name + ' ' + f_tag + (that.required ? ' (*)' : '') +'</td>' +
												'<td><input id="' + that.tag + '_'+ field +'" name="merge_vars[' + that.tag + '][' + field + ']" type="text" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" /></td>' +
												'</tr>');

											if (extra != '') {
												merge_vars.append('<tr><td colspan="2"><pre>'+ extra +'</pre></td></tr>');
											}
										});
									} else {
										merge_vars.append('<tr><td>(' + this.tag + ') ' + this.name + (this.required ? ' (*)' : '') +'</td><td><input id="' + this.tag + '" name="merge_vars[' + this.tag + ']" type="text" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" /></td></tr>');

										if (typeof this.extra != 'undefined') {
											merge_vars.append('<tr><td colspan="2"><pre>'+ this.extra +'</pre></td></tr>');
										}
									}
								});
							}

							merge_vars.find('[data-placeholders]:not(#EMAIL)').rsplaceholder();

							interest_groups.find("tr").remove();
							if (response.interest_groups.length > 0) {
								jQuery.each(response.interest_groups, function () {
									interest_groups.append('<tr><td>' + this.title + '</td><td><select name="interest_groups[' + this.title + ']">' +
										<?php foreach ($fields_array as $field) { ?>
										'<option value="<?php echo $field ?>"><?php echo $field ?></option>' +
										<?php } ?>
										'</select></td></tr>');

									var replace = [];
									jQuery.each(this.subgroups, function () {
										var $val = this.id + '|' + this.title;
										replace.push($val);
									});

									interest_groups.append('<tr><td colspan="2">' + Joomla.JText._('RSFP_MAILCHIMP_INTEREST_GROUP_DESC').replace('%s', replace.join("\n")) + '</td></tr>');
								});
							}

							var suggestions = jQuery('#mc_tags_suggestions');
							suggestions.empty();
							if (response.tags.length > 0) {
								var available_tags = []
								jQuery.each(response.tags, function (index, tag) {
									available_tags.push(tag);
								});

								suggestions.parent().css('display', 'table-row');
								suggestions.append(Joomla.JText._('RSFP_MAILCHIMP_TAGS_AVAILABLE_DESC').replace('%s', available_tags.join("\n")));
							} else {
								suggestions.parent().css('display', 'none');
							}

							// clear the tags when the list is changed
							jQuery('#mc_tags').val('');
						},
						dataType: 'json'
					});
				}

				function mcChangeEmailType(value) {
					jQuery('[name="mailchimp[mc_email_type_field]"]').prop('disabled', value !== 'user');
				}

				function mcChangeAction(value) {
					jQuery('[name="mailchimp[mc_action_field]"]').prop('disabled', value !== '2');
				}

				function mcToggleTagOptions(status){
					var $option = jQuery('#rsf_tag_option');
					parseInt(status) ? $option.show() : $option.hide() ;
				}
			</script>
			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_NAME'); ?></h3>
			<p><?php echo HTMLHelper::_('image', 'administrator/components/com_rsform/assets/images/mailchimp.png', 'mailchimp'); ?></p>
			<div class="alert alert-info"><?php echo Text::_('RSFP_MAILCHIMP_DESC'); ?></div>
			<table class="table table-bordered">
				<tr>
					<td style="width: 1%" nowrap><?php echo Text::_('RSFP_MAILCHIMP_USE_INTEGRATION'); ?></td>
					<td><?php echo $lists['published']; ?></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_ACTION_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_ACTION'); ?></span>
					</td>
					<td><?php echo $lists['mc_action']; ?><?php echo $lists['mc_action_field']; ?>
					<p><?php echo Text::_('RSFP_MAILCHIMP_ACTION_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap><?php echo Text::_('RSFP_MAILCHIMP_LIST_ID'); ?></td>
					<td><?php echo $lists['mc_list_id']; ?></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_EMAIL_TYPE_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_EMAIL_TYPE'); ?></span>
					</td>
					<td><?php echo $lists['mc_email_type']; ?><?php echo $lists['mc_email_type_field']; ?>
					<p><?php echo Text::_('RSFP_MAILCHIMP_EMAIL_TYPE_WARNING'); ?></p></td>
				</tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_SUBSCRIBE_OPTIONS'); ?></h3>
			<table class="table table-bordered">
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_DOUBLE_OPTIN_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_DOUBLE_OPTIN'); ?></span>
					</td>
					<td><?php echo $lists['mc_double_optin']; ?></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_TRIGGER_TAGS_AUTOMATION_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_TRIGGER_TAGS_AUTOMATION'); ?></span>
					</td>
					<td><?php echo $lists['mc_trigger_tags_automation']; ?></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_UPDATE_EXISTING_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_UPDATE_EXISTING'); ?></span>
					</td>
					<td><?php echo $lists['mc_update_existing']; ?></td>
				</tr>
				<tr id="rsf_tag_option"<?php echo ($row->mc_update_existing ? '' : ' style="display:none"'); ?>>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_APPEND_TAGS_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_APPEND_TAGS'); ?></span>
					</td>
					<td><?php echo $lists['mc_append_tags']; ?></td>
				</tr>
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_REPLACE_INTERESTS_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_REPLACE_INTERESTS'); ?></span>
					</td>
					<td><?php echo $lists['mc_replace_interests']; ?></td>
				</tr>
                <tr>
                    <td style="width: 1%" nowrap>
                        <span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_LANGUAGE_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_LANGUAGE'); ?></span>
                    </td>
                    <td><input size="100" maxlength="255" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" type="text" name="mailchimp[mc_language]" value="<?php echo !empty($row->mc_language) ? htmlspecialchars($row->mc_language, ENT_COMPAT, 'utf-8') : ''; ?>" /></td>
                </tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_UNSUBSCRIBE_OPTIONS'); ?></h3>
			<table class="table table-bordered">
				<tr>
					<td style="width: 1%" nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('RSFP_MAILCHIMP_DELETE_MEMBER_DESC'); ?>"><?php echo Text::_('RSFP_MAILCHIMP_DELETE_MEMBER'); ?></span>
					</td>
					<td><?php echo $lists['mc_delete_member']; ?></td>
				</tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_MERGE_VARS'); ?></h3>
			<p><?php echo Text::_('RSFP_MAILCHIMP_MERGE_VARS_DESC'); ?></p>
			<table class="table table-bordered">
				<tbody id="merge_vars">
				<tr>
					<td>(EMAIL) Email (*)</td>
					<td><input id="EMAIL" data-delimiter=" " data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" name="merge_vars[EMAIL]" value="<?php echo isset($row->mc_merge_vars['EMAIL']) ? $row->mc_merge_vars['EMAIL'] : null;?>" type="text"></td>
				</tr>
				<?php
				if (is_array($merge_vars))
				{
					foreach ($merge_vars as $merge_var)
					{
						if (is_array($lists['fields'][$merge_var->tag]['field'])) {
							foreach($lists['fields'][$merge_var->tag]['field'] as $field_name => $field) {
								?>
								<tr>
									<td>(<?php echo $merge_var->tag; ?>) <?php echo $merge_var->name. ' '. Text::_('RSFP_MAILCHIMP_VARS_ARRAY_'.(strtoupper($field_name))) . ($merge_var->required ? ' (*)' : ''); ?></td>
									<td><?php echo $field['field']; ?></td>
								</tr>
								<?php
								if (isset($field['extra'])) {
									?>
									<tr>
										<td colspan="2"><pre><?php echo $field['extra']; ?></pre></td>
									</tr>
									<?php
								}
							}
						} else {
							?>
							<tr>
								<td>(<?php echo $merge_var->tag; ?>) <?php echo $merge_var->name . ($merge_var->required ? ' (*)' : ''); ?></td>
								<td><?php echo $lists['fields'][$merge_var->tag]['field']; ?></td>
							</tr>
							<?php
							if (isset($lists['fields'][$merge_var->tag]['extra'])) {
								?>
								<tr>
									<td colspan="2"><pre><?php echo $lists['fields'][$merge_var->tag]['extra']; ?></pre></td>
								</tr>
								<?php
							}
						}
					}
				}
				?>
				</tbody>
			</table>
			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_INTERESTS'); ?></h3>
			<p><?php echo Text::_('RSFP_MAILCHIMP_INTERESTS_DESC'); ?></p>
			<table class="table table-bordered">
				<tbody id="interest_groups">
				<?php
				if (is_array($interest_groups))
				{
					foreach ($interest_groups as $interest_group)
					{
						?>
						<tr>
							<td><?php echo $interest_group->title; ?></td>
							<td><?php echo $lists['fields_groups'][$interest_group->id]; ?></td>
						</tr>
						<tr>
							<td colspan="2"><?php echo Text::sprintf('RSFP_MAILCHIMP_INTEREST_GROUP_DESC', $lists['field_groups_desc'][$interest_group->id]); ?><?php echo $lists['cached_values'][$interest_group->id]; ?></td>
						</tr>
						<?php
					}
				}
				?>
				</tbody>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_MAILCHIMP_TAGS'); ?></h3>
			<p><?php echo Text::_('RSFP_MAILCHIMP_TAGS_DESC'); ?></p>
			<table class="table table-bordered">
				<tbody id="tag_groups">
				<tr>
					<td colspan="2" style="text-align: center"><input id="mc_tags" data-delimiter="," data-filter-type="include" data-filter="value,path,localpath,text,global" data-placeholders="display" size="100" maxlength="64" name="mc_tags" value="<?php echo RSFormProHelper::htmlEscape($row->mc_tags); ?>" type="text"></td>
				</tr>
				<tr<?php if (empty($tag_lists)) { ?> style="display:none" <?php } ?>>
					<td colspan="2" id="mc_tags_suggestions"><?php echo Text::sprintf('RSFP_MAILCHIMP_TAGS_AVAILABLE_DESC', implode("\n", $tag_lists)); ?></td>
				</tr>

				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Button from the Form Properties Menu ( LEFT SIDE )
	 */
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		echo '<li><a href="javascript: void(0);" id="mailchimp"><span class="rsficon rsficon-envelope-o"></span><span class="inner-text">' . Text::_('RSFP_MAILCHIMP_INTEGRATION') . '</span></a></li>';
	}

	/**
	 * Hook in the RSForm!Pro submission storing process.
	 *
	 * @param $args
	 *
	 * @return bool
	 */
	public function onRsformFrontendBeforeStoreSubmissions($args)
	{
		$formId = (int) $args['formId'];
		$row 	= $this->getTable();

		if ($row && $row->load($formId))
		{
			if (!$row->mc_list_id || !$row->mc_published)
			{
				return false;
			}

			$row->mc_merge_vars = @unserialize($row->mc_merge_vars);
			if ($row->mc_merge_vars === false)
			{
				$row->mc_merge_vars = array();
			}
			$row->mc_cached_values = @unserialize($row->mc_cached_values);
			if ($row->mc_cached_values === false)
			{
				$row->mc_cached_values = array();
			}
			if (is_array($row->mc_cached_values))
			{
				foreach ($row->mc_cached_values as $group => $values)
				{
					$row->mc_cached_values[$group] = json_decode($values, true);
				}
			}
			if (empty($row->mc_merge_vars['EMAIL']))
			{
				return false;
			}

			$row->mc_interest_groups = @unserialize($row->mc_interest_groups);
			if ($row->mc_interest_groups === false)
			{
				$row->mc_interest_groups = array();
			}
			
			$merge_vars = $row->mc_merge_vars;

			$form          = $args['post'];
			$email_address = $row->mc_merge_vars['EMAIL'];

			// Interest Groups
			$merge_interest = array();

			if (!empty($row->mc_interest_groups))
			{
				foreach ($row->mc_interest_groups as $group => $field)
				{
					if ($field == '- IGNORE -' || empty($form[$field]))
					{
						continue;
					}

					$interests = array();
					if (is_array($form[$field]))
					{
						$interests = array_merge($interests, $form[$field]);
					}
					else
					{
						$interests[] = $form[$field];
					}
					
					if (isset($row->mc_cached_values[$group]))
					{
						foreach ($interests as $key => $value)
						{
							if (isset($row->mc_cached_values[$group][$value]))
							{
								$interests[$key] = $row->mc_cached_values[$group][$value];
							}
						}
					}

					$merge_interest[] = array(
						'name'   => $group,
						'groups' => $interests
					);
				}
			}

			// Email Type
			$email_type = $row->mc_email_type;
			$valid      = array('html', 'text', 'mobile');
			if ($row->mc_email_type == 'user')
			{
				$email_type = 'html';

				if (isset($form[$row->mc_email_type_field]))
				{
					if (is_array($form[$row->mc_email_type_field]))
					{
						$email_type_field = implode('', $form[$row->mc_email_type_field]);
					}
					else
					{
						$email_type_field = $form[$row->mc_email_type_field];
					}
					$email_type_field = strtolower(trim($email_type_field));
					if (in_array($email_type_field, $valid))
					{
						$email_type = $email_type_field;
					}
				}
			}

			// Subscribe action - Subscribe, Unsubscribe or Let the user choose
			$subscribe = '';
			if ($row->mc_action == 1)
			{
				$subscribe = 'subscribe';
			}
			elseif ($row->mc_action == 0)
			{
				$subscribe = 'unsubscribe';
			}
			elseif ($row->mc_action == 2 && isset($form[$row->mc_action_field]))
			{
				if (is_array($form[$row->mc_action_field]))
				{
					foreach ($form[$row->mc_action_field] as $i => $value)
					{
						$value = strtolower(trim($value));
						if ($value == 'subscribe')
						{
							$subscribe = 'subscribe';
							break;
						}
						elseif ($value == 'unsubscribe')
						{
							$subscribe = 'unsubscribe';
							break;
						}
					}
				}
				else
				{
					$form[$row->mc_action_field] = strtolower(trim($form[$row->mc_action_field]));
					if ($form[$row->mc_action_field] == 'subscribe')
					{
						$subscribe = 'subscribe';
					}
					elseif ($form[$row->mc_action_field] == 'unsubscribe')
					{
						$subscribe = 'unsubscribe';
					}
				}
			}

			$this->mailchimpData = array(
				'row'               		=> $row,
				'subscribe'         		=> $subscribe,
				'list_id'           		=> $row->mc_list_id,
				'email_address'     		=> $email_address,
				'merge_vars'        		=> $merge_vars,
				'email_type'        		=> $email_type,
				'double_optin'      		=> $row->mc_double_optin,
				'update_existing'   		=> $row->mc_update_existing,
				'replace_interests' 		=> $row->mc_replace_interests,
				'delete_member'     		=> $row->mc_delete_member,
				'tags'     					=> $row->mc_tags,
				'append_tags'     			=> $row->mc_append_tags,
				'trigger_tags_automation'   => (bool)$row->mc_trigger_tags_automation,
				'interests'         		=> $merge_interest
			);
		}

		return true;
	}

	protected function cleanTags($tags)
	{
		$tags = explode(',', $tags);
		$tags = array_filter(array_map('trim', $tags));

		return $tags;
	}

	/**
	 * Hook after placeholders are created
	 *
	 * @param $args
	 */
	public function onRsformAfterCreatePlaceholders($args)
	{
		// Workaround so that uploads are sent to MailChimp
		if (!empty($this->mailchimpData))
		{
			require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/mcapi.php';

			$mailchimp 		= RSFormPro_Mailchimp::getInstance();
			$mailchimpData 	= $this->mailchimpData;

			// Unset the MailChimp object now that we're done with it.
			$this->mailchimpData = null;

			$merged_vars_replaced = new stdClass();
			foreach ($mailchimpData['merge_vars'] as $m_var => $values)
			{
				$merged_vars_replaced->{$m_var} = str_replace($args['placeholders'], $args['values'], $values);

				if (is_array($values))
				{
					$merged_vars_replaced->{$m_var} = (object) $merged_vars_replaced->{$m_var};
				}
			}

			$data = array(
				'email_address' => str_replace($args['placeholders'], $args['values'], $mailchimpData['email_address']),
				'merge_fields'  => $merged_vars_replaced,
				'email_type'    => $mailchimpData['email_type'],
				'interests'     => $mailchimpData['interests'],
			);

			if ($mailchimpData['subscribe'] == 'subscribe' || $mailchimpData['subscribe'] == 'unsubscribe')
			{
				$tags_found = array();
				if (!empty($mailchimpData['tags'])) {
					// replace the placeholders used in tags
					$mailchimpData['tags'] = str_replace($args['placeholders'], $args['values'], $mailchimpData['tags']);

					if ($args['form']->MultipleSeparator != ',') {
						$separator = str_replace(array('\n', '\r', '\t'), array("\n", "\r", "\t"), $args['form']->MultipleSeparator);

						$mailchimpData['tags'] = str_replace($separator, ',', $mailchimpData['tags']);
					}

					$tags = $this->cleanTags($mailchimpData['tags']);

					if (!empty($tags)) {
						foreach ($tags as $tag) {
							$tags_found[] = $tag;
						}
					}
				}

				// Subscribing?
				if ($mailchimpData['subscribe'] == 'subscribe')
				{
					$contact_status = 'pending';
					if ($mailchimpData['double_optin'] || !$mailchimpData['update_existing'])
					{
						if ($status_data = $mailchimp->get_user_status($mailchimpData['list_id'], $data['email_address']))
						{
							if ($status_data->status == 'subscribed')
							{
								$contact_status = 'subscribed';
							}
						}
					}
					
					$data['status'] = $mailchimpData['double_optin'] ? $contact_status : 'subscribed';
				}
				// Unsubscribing
				else
				{
					$data['status'] = 'unsubscribed';
				}

				if (!empty($mailchimpData['row']->mc_language))
				{
                    $data['language'] = str_replace($args['placeholders'], $args['values'], $mailchimpData['row']->mc_language);

                    if (strpos($data['language'], '-') !== false)
					{
                        list($data['language'], ) = explode('-', $data['language'], 2);
					}
				}

				$user = $mailchimp->manage_user($mailchimpData['list_id'], $mailchimpData['update_existing'], $mailchimpData['replace_interests'], $mailchimpData['delete_member'], $data, isset($status_data) ? $status_data : null);

				if ($mailchimpData['subscribe'] == 'subscribe' && $user && !empty($user->marketing_permissions))
				{
					$permissions = array();
					foreach ($user->marketing_permissions as $permission)
					{
						$permissions[] = array(
							'marketing_permission_id' => $permission->marketing_permission_id,
							'enabled' => true
						);
					}

					if ($permissions)
					{
						$mailchimp->update_user($mailchimpData['list_id'], $data['email_address'], array('marketing_permissions' => $permissions));
					}
				}

				if (!empty($tags_found))
				{
					$all_tags = array();

					if (!$mailchimpData['append_tags'])
					{
						$old_tags = $mailchimp->get_user_tags($mailchimpData['list_id'], $data['email_address']);
						if (!empty($old_tags))
						{
							foreach ($old_tags as $old_tag)
							{
								if (!in_array($old_tag->name, $tags_found))
								{
									$all_tags[] = array('name' => $old_tag->name, 'status' => 'inactive');
								}
							}
						}
					}

					foreach($tags_found as $tag)
					{
						$all_tags[] = array('name' => $tag, 'status' => 'active');
					}

					// When is_syncing is true, automations based on the tags in the request will not fire (so if the stored value is true we have to change it to false)
					$is_syncing = !$mailchimpData['trigger_tags_automation'];

					$mailchimp->update_user_tags($mailchimpData['list_id'], $data['email_address'], $all_tags, $is_syncing);
				}
			}
		}
	}

	/**
	 * Function to generate the Tabs
	 *
	 * @param $tabs
	 */
	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('RSFP_MAILCHIMP_NAME'), 'page-mailchimp');
		$tabs->addContent($this->configurationScreen());
	}

	/**
	 * Create the mailchimp configuration screen
	 *
	 * @return string
	 */
	public function configurationScreen()
	{
		ob_start();

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

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

		?>
		<div id="page-mailchimp" class="form-horizontal">
			<p><?php echo Text::_('RSFP_MAILCHIMP_API_KEY_INFO'); ?></p>
			<?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('mailchimp.%', false));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}

	/**
	 * Function that handles the AJAX requests
	 *
	 * @throws Exception
	 */
	public function onRsformBackendSwitchTasks()
	{
		$app		 = Factory::getApplication();
		$input       = $app->input;
		$plugin_task = $input->getString('plugin_task', '');

		switch ($plugin_task)
		{
			case 'mailchimp.get_merge_vars':
				require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/mcapi.php';
				$mailchimp = RSFormPro_Mailchimp::getInstance();

				if ($list_id = $input->post->get('list_id', '', 'string'))
				{
					$response = array(
						'merge_vars' 		=> array(),
						'interest_groups' 	=> array(),
						'tags' 				=> array()
					);

					if ($merge_fields = $mailchimp->get_merge_fields($list_id))
					{
						foreach ($merge_fields as $m_field)
						{
							if ($m_field->type == 'address')
							{
								$array_values = array(
									'addr1' 	=> Text::_('RSFP_MAILCHIMP_VARS_ARRAY_ADDR1'),
									'addr2' 	=> Text::_('RSFP_MAILCHIMP_VARS_ARRAY_ADDR2'),
									'city' 		=> Text::_('RSFP_MAILCHIMP_VARS_ARRAY_CITY'),
									'state' 	=> Text::_('RSFP_MAILCHIMP_VARS_ARRAY_STATE'),
									'zip' 		=> Text::_('RSFP_MAILCHIMP_VARS_ARRAY_ZIP'),
									'country' 	=> array('label' => Text::_('RSFP_MAILCHIMP_VARS_ARRAY_COUNTRY'), 'extra' => Text::_('RSFP_MAILCHIMP_VARS_ARRAY_COUNTRY_DESC')),

								);

								$m_field->address_fields = $array_values;
							}
							else if($m_field->type == 'birthday')
							{
								$m_field->extra = Text::sprintf('RSFP_MAILCHIMP_BIRTHDAY_FIELD_FORMAT', $m_field->options->date_format);
							}

							if (!empty($m_field->options->choices))
							{
								$extra = array(Text::_('RSFP_MAILCHIMP_CHOICES_AVAILABLE'));
								foreach ($m_field->options->choices as $choice)
								{
									$extra[] = $choice;
								}
								$extra = implode('<br/>', $extra);

								$m_field->extra = $extra;
							}
						}

						$response['merge_vars'] = $merge_fields;
					}

					$tag_names = array();
					if ($tags = $mailchimp->get_tags($list_id))
					{
						foreach ($tags as $tag)
						{
							$tag_names[] = $tag->name;
						}
					}

					$response['tags'] = $tag_names;

					$interest_groups = array();
					if ($categories = $mailchimp->get_interest_categories($list_id))
					{
						foreach ($categories as $category)
						{
							$interest = array(
								'title' 	=> $category->title,
								'subgroups' => array()
							);

							if ($interests = $mailchimp->get_interests($list_id, $category->id))
							{
								foreach ($interests as $subgroup)
								{
									$interest['subgroups'][] = array('title' => $subgroup->name, 'id' => $subgroup->id);
								}
							}

							$interest_groups[] = $interest;
						}
					}

					$response['interest_groups'] = $interest_groups;
				}

				echo json_encode($response);

				$app->close();
			break;
		}
	}

	/**
	 * Helper function to get the form fields
	 *
	 * @param $formId
	 *
	 * @return mixed
	 */
	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'));

		$fields = $db->setQuery($query)->loadColumn();
		array_unshift($fields, '- IGNORE -');

		return $fields;
	}

	public function onRsformBackendFormCopy($args)
	{
		$formId = $args['formId'];
		$newFormId = $args['newFormId'];

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

	/**
	 * Handle uninstall
	 *
	 * @param $formId
	 */
	public function onRsformFormDelete($formId)
	{
		if ($row = $this->getTable())
		{
			$row->delete($formId);
		}
	}

	/**
	 * Handle Form Backup
	 *
	 * @param $form
	 * @param $xml
	 * @param $fields
	 */
	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('mailchimp');
				foreach ($data as $property => $value)
				{
					$xml->add($property, $value);
				}
				$xml->add('/mailchimp');
			}
		}
	}

	/**
	 * Handle Form Restores
	 *
	 * @param $form
	 * @param $xml
	 * @param $fields
	 */
	public function onRsformFormRestore($form, $xml, $fields)
	{
		if (isset($xml->mailchimp))
		{
			$data = array(
				'form_id' => $form->FormId
			);

			foreach ($xml->mailchimp->children() as $property => $value)
			{
				$data[$property] = (string) $value;
			}

			$row = $this->getTable();
			
			// Migrate to new version
			if (isset($data['mc_send_welcome']))
			{
				$data['mc_merge_vars'] = @unserialize($data['mc_merge_vars']);
				if (!is_array($data['mc_merge_vars']))
				{
					$data['mc_merge_vars'] = array();
				}
				$new_merge_vars = array();
				foreach ($data['mc_merge_vars'] as $merge_var => $field)
				{
					$new_merge_vars[$merge_var] = '';
					if ($field != '- IGNORE -')
					{
						if ($exists = RSFormProHelper::componentNameExists($field, $form->FormId, 0, 'ComponentTypeId'))
						{
							if ($exists[0] == RSFORM_FIELD_FILEUPLOAD)
							{
								$new_merge_vars[$merge_var] = '{' . $field . ':path}';
							}
							else
							{
								$new_merge_vars[$merge_var] = '{' . $field . ':value}';
							}
						}
					}
				}
				
				$data['mc_merge_vars'] = serialize($new_merge_vars);
			}

			$row->save($data);
		}
	}

	/**
	 * Truncate tables on restores
	 */
	public function onRsformBackendFormRestoreTruncate()
	{
		Factory::getDbo()->truncateTable('#__rsform_mailchimp');
	}
}