<?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 plgSystemRsfpsalesforcecase extends CMSPlugin
{
	protected $autoloadLanguage = true;

	public function onRsformFormSave($form)
	{
		$app                         = Factory::getApplication();
		$data                        = $app->input->post->get('salesforcecase', array(), 'array');
		$names                       = $app->input->post->get('slsfc_api_name', array(), 'array');
		$values                      = $app->input->post->get('slsfc_value', array(), 'array');
		$data['form_id']             = $form->FormId;
		$data['slsfc_custom_fields'] = array();

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

		if ($names && $values)
		{
			for ($i = 0; $i < count($names); $i++)
			{
				$data['slsfc_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_Salesforcecase', '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->slsfc_custom_fields = !empty($row->slsfc_custom_fields) ? unserialize($row->slsfc_custom_fields) : array();

		$lists = array(
			'published' => RSFormProHelper::renderHTML('select.booleanlist', 'salesforcecase[slsfc_published]', '', $row->slsfc_published),
			'debug' => RSFormProHelper::renderHTML('select.booleanlist', 'salesforcecase[slsfc_debug]', 'onclick="salesforcecaseEnableDebug(this.value)"', $row->slsfc_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_RSFPSALESFORCECASE_ACTION_SUBSCRIBE')),
			HTMLHelper::_('select.option', 2, Text::_('PLG_SYSTEM_RSFPSALESFORCECASE_LET_USER_DECIDE'))
		);
		$lists['action'] = HTMLHelper::_('select.genericlist', $action, 'salesforcecase[slsfc_action]', 'onchange="salesforcecaseChangeAction(this.value);"', 'value', 'text', $row->slsfc_action);

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

		Text::script('RSFP_SLSFC_CUSTOM_FIELD_API_NAME');
		Text::script('RSFP_SLSFC_CUSTOM_FIELD_API_VALUE');
		Text::script('RSFP_DELETE');
		Text::script('PLG_SYSTEM_RSFPSALESFORCECASE_ARE_YOU_SURE_DELETE_CUSTOM_FIELD');

		?>
		<div id="salesforcecasediv">
		<script type="text/javascript">
			function salesforcecaseChangeAction(value)
			{
				document.getElementsByName('salesforcecase[slsfc_action_field]')[0].disabled = value !== '2';
			}

			function salesforcecaseEnableDebug(value)
			{
				document.getElementById('slsfc_debugEmail').disabled = value !== '1';
			}

			function salesforcecaseAddCustomField()
			{
				var table = document.getElementById('tableSalesforcecaseCustomFields');

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

                var x, y, input;

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

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

				y = x.insertCell(1);
				input = document.createElement('input');
				input.type = 'text';
				input.name = 'slsfc_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() {
					deleteSalesforceCustomFieldcase(id);
				});
				y.appendChild(button);

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

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

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

			function deleteSalesforceCustomFieldcase(id)
			{
                if (confirm(Joomla.JText._('PLG_SYSTEM_RSFPSALESFORCECASE_ARE_YOU_SURE_DELETE_CUSTOM_FIELD')))
                {
                    document.getElementById('slsfc_api_name' + id).parentNode.removeChild(document.getElementById('slsfc_api_name' + id));
                    document.getElementById('slsfc_value' + id).parentNode.removeChild(document.getElementById('slsfc_value' + id));
                }
			}
		</script>
			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_SALESFORCE_CASE_INTEGRATION'); ?></h3>
			<div class="alert alert-info"><?php echo Text::_('RSFP_SALESFORCECASE_DESC'); ?></div>

			<table class="table table-bordered">
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_USE_INTEGRATION'); ?></td>
					<td><?php echo $lists['published']; ?></td>
				</tr>
				<tr>
					<td nowrap>
						<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCECASE_ACTION_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCECASE_ACTION'); ?></span>
					</td>
					<td nowrap="nowrap"><?php echo $lists['action']; ?><?php echo $lists['action_field']; ?>
					<p><?php echo Text::_('PLG_SYSTEM_RSFPSALESFORCECASE_ACTION_WARNING'); ?></p></td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_ORGID'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_orgid]" id="slsfc_orgid" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_orgid); ?>" class="rs_inp rs_80" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_DEBUG'); ?></td>
					<td><?php echo $lists['debug']; ?></td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_DEBUG_EMAIL'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_debugEmail]" id="slsfc_debugEmail" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_debugEmail); ?>" class="rs_inp rs_80" <?php if (!$row->slsfc_published || !$row->slsfc_debug) { ?>disabled="disabled"<?php } ?> />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_NAME'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_name]" id="slsfc_name" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_name); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_EMAIL'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_email]" id="slsfc_email" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_email); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_PHONE'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_phone]" id="slsfc_phone" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_phone); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_SUBJECT'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_subject]" id="slsfc_subject" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_subject); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_DESCRIPTION'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_description]" id="slsfc_description" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_description); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_COMPANY'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_company]" id="slsfc_company" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_company); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_TYPE'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_type]" id="slsfc_type" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_type); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_STATUS'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_status]" id="slsfc_status" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_status); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_REASON'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_reason]" id="slsfc_reason" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_reason); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
				<tr>
					<td nowrap><?php echo Text::_('RSFP_SLSFC_PRIORITY'); ?></td>
					<td>
						<input type="text" name="salesforcecase[slsfc_priority]" id="slsfc_priority" value="<?php echo RSFormProHelper::htmlEscape($row->slsfc_priority); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					</td>
				</tr>
			</table>

			<h3 class="rsfp-legend"><?php echo Text::_('RSFP_SLSFC_CUSTOM_FIELDS'); ?></h3>
			<p><button class="btn btn-primary" type="button" onclick="salesforcecaseAddCustomField();"><?php echo Text::_('RSFP_SLSFC_ADD_CUSTOM_FIELD'); ?></button></p>
			<table id="tableSalesforcecaseCustomFields" class="table table-bordered">
				<?php
				foreach ($row->slsfc_custom_fields as $i => $field)
				{
					?>
					<tr id="slsfc_api_name<?php echo $i; ?>">
						<td nowrap><?php echo Text::_('RSFP_SLSFC_CUSTOM_FIELD_API_NAME'); ?></td>
						<td><input type="text" name="slsfc_api_name[]" value="<?php echo RSFormProHelper::htmlEscape($field->api_name); ?>" class="rs_inp rs_50" /><button class="btn btn-danger" type="button" onclick="deleteSalesforceCustomFieldcase(<?php echo $i; ?>)"><?php echo Text::_('RSFP_DELETE'); ?></button></td>
					</tr>
					<tr id="slsfc_value<?php echo $i; ?>">
						<td nowrap><?php echo Text::_('RSFP_SLSFC_CUSTOM_FIELD_API_VALUE'); ?></td>
						<td><input type="text" name="slsfc_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="salesforcecase"><span class="rsficon rsficon-cloud"></span><span class="inner-text"><?php echo Text::_('RSFP_SALESFORCE_CASE_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_salesforcecase'))
			->where($db->qn('form_id') . ' = ' . $db->q($formId))
			->where($db->qn('slsfc_published') . ' = ' . $db->q(1));

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

			if ($row->slsfc_action == 2)
			{
				$value = str_replace($replace, $with, $row->slsfc_action_field);
				if ($value != 'subscribe')
				{
					return;
				}
			}
  
			$data = array(
				'orgid' 		=> $row->slsfc_orgid,
				'name' 			=> $row->slsfc_name,
				'email' 		=> $row->slsfc_email,
				'phone' 		=> $row->slsfc_phone,
				'subject' 		=> $row->slsfc_subject,
				'description' 	=> $row->slsfc_description,
				'company' 		=> $row->slsfc_company,
				'type' 			=> $row->slsfc_type,
				'status' 		=> $row->slsfc_status,
				'reason' 		=> $row->slsfc_reason,
				'priority' 		=> $row->slsfc_priority
			);
			
			$row->slsfc_custom_fields = !empty($row->slsfc_custom_fields) ? unserialize($row->slsfc_custom_fields) : array();
			if (!empty($row->slsfc_custom_fields))
			{
				foreach ($row->slsfc_custom_fields as $field)
				{
					$data[$field->api_name] = $field->value;
				}
			}
			
			$data['debug'] = (int) $row->slsfc_debug;
			if ($row->slsfc_debug)
			{
				$data['debugEmail'] = $row->slsfc_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('salesforcecase.webtocase_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_SALESFORCECASE_LABEL'), 'page-salesforcecase');
		$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('salesforcecase.webtocase_url', 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_rsfpsalesforcecase.configuration', 'configuration', array('control' => 'rsformConfig'), false, false );
		$form->bind($this->loadFormData());

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