<?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\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Http\HttpFactory;

class plgSystemRsfpsalesforce extends CMSPlugin
{
	protected $autoloadLanguage = true;

	public function onRsformFormSave($form)
	{
		$app                        = Factory::getApplication();
		$data                       = $app->input->post->get('salesforce', array(), 'array');
		$names                      = $app->input->post->get('slsf_api_name', array(), 'array');
		$values                     = $app->input->post->get('slsf_value', array(), 'array');
		$data['form_id']            = $form->FormId;
		$data['slsf_custom_fields'] = array();
		
		$row = $this->getTable();
		if (!$row)
		{
			return false;
		}

		if ($names && $values)
		{
			for ($i = 0; $i < count($names); $i++)
			{
				$data['slsf_custom_fields'][] = (object) array(
					'api_name' 	=> $names[$i],
					'value'		=> $values[$i]
				);
			}
		}

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

	protected function getTable()
	{
		return Table::getInstance('RSForm_Salesforce', 'Table');
	}
	
	public function onRsformBackendFormCopy($args)
	{
		$formId = $args['formId'];
		$newFormId = $args['newFormId'];

		if ($row = $this->getTable() )
		{
			if ($row->load($formId))
			{
				if (!$row->bind(array('form_id'=>$newFormId)))
				{
					return false;
				}

				$row->check();

				return $row->store();
			}
		}
	}
	
	public function onRsformBackendAfterShowFormEditTabs()
	{
		$formId = Factory::getApplication()->input->getInt('formId');
		
		$row = $this->getTable();
		if (!$row)
		{
			return;
		}

		$row->load($formId);
		$row->slsf_custom_fields = !empty($row->slsf_custom_fields) ? unserialize($row->slsf_custom_fields) : array();

		$lists = array(
			'published' => RSFormProHelper::renderHTML('select.booleanlist', 'salesforce[slsf_published]', '', $row->slsf_published),
			'debug' => RSFormProHelper::renderHTML('select.booleanlist', 'salesforce[slsf_debug]', 'onclick="salesforceEnableDebug(this.value)"',$row->slsf_debug)
		);

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

		// Action
		$action = array(
			HTMLHelper::_('select.option', 1, Text::_('PLG_SYSTEM_RSFPSALESFORCE_ACTION_SUBSCRIBE')),
			HTMLHelper::_('select.option', 2, Text::_('PLG_SYSTEM_RSFPSALESFORCE_LET_USER_DECIDE'))
		);
		$lists['action'] = HTMLHelper::_('select.genericlist', $action, 'salesforce[slsf_action]', 'onchange="salesforceChangeAction(this.value);"', 'value', 'text', $row->slsf_action);

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

		Text::script('RSFP_SLSF_CUSTOM_FIELD_API_NAME');
		Text::script('RSFP_SLSF_CUSTOM_FIELD_API_VALUE');
		Text::script('RSFP_DELETE');
		Text::script('PLG_SYSTEM_RSFPSALESFORCE_ARE_YOU_SURE_DELETE_CUSTOM_FIELD');

		?>
		<div id="salesforcediv">
		<script type="text/javascript">
			function salesforceChangeAction(value)
			{
				document.getElementsByName('salesforce[slsf_action_field]')[0].disabled = value !== '2';
			}

			function salesforceEnableDebug(value)
			{
				document.getElementById('slsf_debugEmail').disabled = value !== '1';
			}

			function salesforceAddCustomField()
			{
				var table = document.getElementById('tableSalesforceCustomFields');

				// ID
				var id = Math.floor(Math.random()*3+1);

				var x, y, input;

				// API Name
				x = table.insertRow(table.rows.length);
				x.id = 'slsf_api_name' + id;
				x.setAttribute('id', 'slsf_api_name' + id);

				y = x.insertCell(0);
				y.setAttribute('nowrap', 'nowrap');
				y.innerHTML = Joomla.JText._('RSFP_SLSF_CUSTOM_FIELD_API_NAME');

				y = x.insertCell(1);
				input = document.createElement('input');
				input.type = 'text';
				input.name = 'slsf_api_name[]';
				input.placeholder = 'ID';
				input.setAttribute('class', 'rs_inp rs_50');
				y.appendChild(input);

				var button = document.createElement('button');
				button.type = 'button';
				button.setAttribute('class', 'btn btn-danger');
				button.innerHTML = Joomla.JText._('RSFP_DELETE');
				jQuery(button).click(function() {
					salesforceDeleteCustomField(id);
				});
				y.appendChild(button);

				// Value
				x = table.insertRow(table.rows.length);
				x.id = 'slsf_value' + id;
				x.setAttribute('id', 'slsf_value' + id);

				y = x.insertCell(0);
				y.setAttribute('nowrap', 'nowrap');
				y.innerHTML = Joomla.JText._('RSFP_SLSF_CUSTOM_FIELD_API_VALUE');

				y = x.insertCell(1);
				input = document.createElement('input');
				input.type = 'text';
				input.name = 'slsf_value[]';
				input.value = '';
				input.setAttribute('class', 'rs_inp rs_80');
				y.appendChild(input);
			}

			function salesforceDeleteCustomField(id)
			{
			    if (confirm(Joomla.JText._('PLG_SYSTEM_RSFPSALESFORCE_ARE_YOU_SURE_DELETE_CUSTOM_FIELD')))
			    {
                    document.getElementById('slsf_api_name' + id).parentNode.removeChild(document.getElementById('slsf_api_name' + id));
                    document.getElementById('slsf_value' + id).parentNode.removeChild(document.getElementById('slsf_value' + id));
			    }
			}

		</script>
			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_SALESFORCE_INTEGRATION'); ?></h3>
			<div class="alert alert-info"><?php echo Text::_('RSFP_SALESFORCE_DESC'); ?></div>

			<table class="table table-bordered">
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_USE_INTEGRATION'); ?></td>
					<td><?php echo $lists['published']; ?></td>
				</tr>
				<tr>
					<td nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCE_ACTION_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCE_ACTION'); ?></span>
					</td>
					<td nowrap="nowrap"><?php echo $lists['action']; ?><?php echo $lists['action_field']; ?>
					<p><?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCE_ACTION_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_OID'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_oid]" id="slsf_oid" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_oid); ?>" class="rs_inp rs_80" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_DEBUG'); ?></td>
					<td><?php echo $lists['debug']; ?></td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_DEBUG_EMAIL'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_debugEmail]" id="slsf_debugEmail" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_debugEmail); ?>" class="rs_inp rs_80" <?php if (!$row->slsf_published || !$row->slsf_debug) { ?>disabled="disabled"<?php } ?> />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_CAMPAIGN_ID'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_campaign_id]" id="slsf_campaign_id" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_campaign_id); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
                <tr>
                    <td nowrap><?php echo Text::_('RSFP_SLSF_RECORD_TYPE'); ?></td>
                    <td>
                        <input type="text" name="salesforce[slsf_recordtype]" id="slsf_recordtype" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_recordtype); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
                    </td>
                </tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_LEAD_SOURCE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_lead_source]" id="slsf_lead_source" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_lead_source); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
						<br /><small><?php echo Text::_('RSFP_SLSF_LEAD_SOURCE_DESC'); ?></small>
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_DESCRIPTION'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_description]" id="slsf_description" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_description); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_SALUTATION'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_salutation]" id="slsf_salutation" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_salutation); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
						<br /><small><?php echo Text::_('RSFP_SLSF_SALUTATION_DESC'); ?></small>
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_FIRST_NAME'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_first_name]" id="slsf_first_name" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_first_name); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_LAST_NAME'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_last_name]" id="slsf_last_name" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_last_name); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_TITLE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_title]" id="slsf_title" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_title); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_INDUSTRY'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_industry]" id="slsf_industry" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_industry); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_COMPANY'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_company]" id="slsf_company" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_company); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_REVENUE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_revenue]" id="slsf_revenue" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_revenue); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_EMPLOYEES'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_employees]" id="slsf_employees" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_employees); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_WEBSITE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_website]" id="slsf_website" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_website); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_EMAIL'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_email]" id="slsf_email" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_email); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_EMAIL_OPTOUT'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_emailoptout]" id="slsf_emailoptout" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_emailoptout); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_PHONE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_phone]" id="slsf_phone" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_phone); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_DO_NOT_CALL'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_donotcall]" id="slsf_donotcall" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_donotcall); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_MOBILE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_mobile]" id="slsf_mobile" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_mobile); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_FAX'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_fax]" id="slsf_fax" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_fax); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_FAX_OPTOUT'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_faxoptout]" id="slsf_faxoptout" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_faxoptout); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_STREET'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_street]" id="slsf_street" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_street); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_CITY'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_city]" id="slsf_city" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_city); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_STATE'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_state]" id="slsf_state" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_state); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_ZIP'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_zip]" id="slsf_zip" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_zip); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSF_COUNTRY'); ?></td>
					<td>
						<input type="text" name="salesforce[slsf_country]" id="slsf_country" value="<?php echo RSFormProHelper::htmlEscape($row->slsf_country); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
			</table>
			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_SLSF_CUSTOM_FIELDS'); ?></h3>
			<p><button class="btn btn-primary" type="button" onclick="salesforceAddCustomField();"><?php echo Text::_('RSFP_SLSF_ADD_CUSTOM_FIELD'); ?></button></p>
			<table id="tableSalesforceCustomFields" class="table table-bordered">
				<?php
				foreach ($row->slsf_custom_fields as $i => $field)
				{
					?>
					<tr id="slsf_api_name<?php echo $i; ?>">
						<td nowrap><?php echo Text::_('RSFP_SLSF_CUSTOM_FIELD_API_NAME'); ?></td>
						<td><input type="text" name="slsf_api_name[]" value="<?php echo RSFormProHelper::htmlEscape($field->api_name); ?>" class="rs_inp rs_50" /><button class="btn btn-danger" type="button" onclick="salesforceDeleteCustomField(<?php echo $i; ?>)"><?php echo Text::_('RSFP_DELETE'); ?></button></td>
					</tr>
					<tr id="slsf_value<?php echo $i; ?>">
						<td nowrap><?php echo Text::_('RSFP_SLSF_CUSTOM_FIELD_API_VALUE'); ?></td>
						<td><input type="text" name="slsf_value[]" value="<?php echo RSFormProHelper::htmlEscape($field->value); ?>" class="rs_inp rs_80" /></td>
					</tr>
				<?php
				}
				?>
			</table>
		</div>
		<?php
	}

	/**
	 * @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'));

		return $db->setQuery($query)->loadColumn();
	}
	
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		?>
		<li><a href="javascript: void(0);" id="salesforce"><span class="rsficon rsficon-cloud"></span><span class="inner-text"><?php echo Text::_('RSFP_SALESFORCE_INTEGRATION'); ?></span></a></li>
		<?php
	}
	
	public function onRsformFrontendAfterFormProcess($args)
	{
		$db = Factory::getDbo();
		
		$formId = (int) $args['formId'];
		$SubmissionId = (int) $args['SubmissionId'];

		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn('#__rsform_salesforce'))
			->where($db->qn('form_id') . ' = ' . $db->q($formId))
			->where($db->qn('slsf_published') . ' = ' . $db->q(1));

		$db->setQuery($query);
		if ($row = $db->loadObject())
		{
			list($replace, $with) = RSFormProHelper::getReplacements($SubmissionId);
			$replace[] = '\n';
			$with[]	   = "\n";

			if ($row->slsf_action == 2)
			{
				$value = str_replace($replace, $with, $row->slsf_action_field);
				if ($value != 'subscribe')
				{
					return;
				}
			}
			
			$data = array(
				'oid' 			=> $row->slsf_oid,
				'lead_source' 	=> $row->slsf_lead_source,
				'first_name' 	=> $row->slsf_first_name,
				'last_name' 	=> $row->slsf_last_name,
				'title' 		=> $row->slsf_title,
				'company' 		=> $row->slsf_company,
				'email' 		=> $row->slsf_email,
				'phone' 		=> $row->slsf_phone,
				'street' 		=> $row->slsf_street,
				'city' 			=> $row->slsf_city,
				'state' 		=> $row->slsf_state,
				'zip' 			=> $row->slsf_zip,
				'country' 		=> $row->slsf_country,
				'industry' 		=> $row->slsf_industry,
				'description' 	=> $row->slsf_description,
				'mobile' 		=> $row->slsf_mobile,
				'fax' 			=> $row->slsf_fax,
				'URL' 			=> $row->slsf_website,
				'salutation' 	=> $row->slsf_salutation,
				'revenue' 		=> $row->slsf_revenue,
				'employees' 	=> $row->slsf_employees,
				'emailOptOut' 	=> $row->slsf_emailoptout,
				'faxOptOut' 	=> $row->slsf_faxoptout,
				'doNotCall' 	=> $row->slsf_donotcall
			);
			
			if ($row->slsf_campaign_id)
			{
				$data['Campaign_ID'] = $row->slsf_campaign_id; 
			}

			if ($row->slsf_recordtype)
			{
				$data['recordType'] = $row->slsf_recordtype;
			}
			
			$row->slsf_custom_fields = !empty($row->slsf_custom_fields) ? unserialize($row->slsf_custom_fields) : array();
			if (!empty($row->slsf_custom_fields))
			{
				foreach ($row->slsf_custom_fields as $field)
				{
					$data[$field->api_name] = $field->value;
				}
			}
			
			$data['debug'] = (int) $row->slsf_debug;
			if ($row->slsf_debug)
			{
				$data['debugEmail'] = $row->slsf_debugEmail;
			}

			// See if multiple selection fields are being used so we can send the correct data
			$allFields = array();
			foreach (array_values($data) as $value)
			{
				if ($value)
				{
					if (preg_match('/{(.*?):.*}/is', $value, $match))
					{
						$allFields[] = $match[1];
					}
				}
			}

			$multiplePlaceholders = array();

			if ($allFields)
			{
				$query = $db->getQuery(true)
					->select($db->qn('c.ComponentId'))
					->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'))
					->where($db->qn('p.PropertyValue') . ' IN (' . implode(',', $db->q($allFields)) . ')');

				if ($componentIds = $db->setQuery($query)->loadColumn())
				{
					if ($all_data = RSFormProHelper::getComponentProperties($componentIds))
					{
						// Load our form
						$query = $db->getQuery(true)
							->select($db->qn('MultipleSeparator'))
							->from($db->qn('#__rsform_forms'))
							->where($db->qn('FormId') . ' = ' . $db->q($formId));

						// Multiple items separator
						$separator = str_replace(array('\n', '\r', '\t'), array("\n", "\r", "\t"), $db->setQuery($query)->loadResult());

						foreach ($all_data as $componentId => $property)
						{
							if (isset($property['ITEMS']))
							{
								$pos = array_search('{' . $property['NAME'] . ':value}', $replace);

								if ($pos !== false)
								{
									$multiplePlaceholders[$property['NAME']] = explode($separator, $with[$pos]);
								}
							}
						}
					}
				}
			}

			if ($multiplePlaceholders)
			{
				foreach ($data as $field => $value)
				{
					foreach ($multiplePlaceholders as $multiplePlaceholder => $arrayValues)
					{
						if (strpos($value, '{' . $multiplePlaceholder . ':value}') !== false)
						{
							$data[$field] = $arrayValues;
						}
					}

				}
			}

            foreach ($data as $k => $v)
            {
                if (!is_array($v))
                {
	                $data[$k] = str_replace($replace, $with, $v);
                }
            }
			$data = http_build_query($data);
			$data = preg_replace('/%5B[0-9]+%5D/simU', '', $data);
			
			try
			{
				$http 	 = HttpFactory::getHttp();
				$url 	 = RSFormProHelper::getConfig('salesforce.webtolead_url');
				$http->post($url, $data);
			}
			catch (Exception $e)
			{
				Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
			}
		}
	}


	/**
	 * @param $tabs RSTabs
	 */
	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('RSFP_SALESFORCE_LABEL'), 'page-salesforce');
		$tabs->addContent($this->configurationScreen());
	}

	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('salesforce.%', false));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}

	private function configurationScreen()
	{
		ob_start();

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

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

		?>
		<div id="page-salesforce" class="form-horizontal">
			<?php
			foreach ($form->getFieldsets() as $fieldset)
			{
				if ($fields = $form->getFieldset($fieldset->name))
				{
					foreach ($fields as $field)
					{
						echo $form->renderField($field->fieldname);
					}
				}
			}
			?>
		</div>
		<?php

		$contents = ob_get_contents();
		ob_end_clean();

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