<?php
/**
 * @package        RSForm! Pro
 * @copyright  (c) 2007 - 2016 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\Uri\Uri;
use Joomla\CMS\Language\Text;

define('RSFORM_FIELD_SIGNATURE', 2787);

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

	/**
	 * @var int
	 */
	protected $componentId = RSFORM_FIELD_SIGNATURE;

	/**
	 * Change the value of the field to an image in the Manage Directories List View
	 *
	 * @param $items
	 * @param $formId
	 *
	 * @return array
	 */
	public function onRsformAfterManageDirectoriesQuery(& $items, $formId)
	{
		foreach ($items as $i => $item)
		{
			foreach ($items[$i] as $key => $value)
			{
				if (RSFormProHelper::getComponentTypeId($key, $formId) == $this->componentId)
				{
					if ($value)
					{
						$items[$i]->{$key} = '<img src="' . RSFormProHelper::htmlEscape($value) . '" class="rsfp-signature-image" />';
					}
				}
			}
		}

		return $items;
	}

	/**
	 * Add the new placeholder to the quick add list
	 *
	 * @param $placeholders
	 *
	 * @return mixed
	 */
	public function onRsformAfterCreateQuickAddPlaceholders(& $placeholders, $componentId)
	{
		if ($componentId == $this->componentId)
		{
			$placeholders['display'][] = '{' . $placeholders['name'] . ':signature}';
			$placeholders['display'][] = '{' . $placeholders['name'] . ':signature_image}';
			$placeholders['display'][] = '{' . $placeholders['name'] . ':signature_url}';
		}

		return $placeholders;
	}

	/**
	 * @param $formId
	 * @param $submissionId
	 * @param $column
	 *
	 * @return string
	 */
	private function generateImageLink($formId, $submissionId, $column)
	{
		return Uri::root() . 'index.php?option=com_rsform&task=plugin&plugin_task=signature.image&hash=' . md5($formId . $submissionId . $column . Factory::getConfig()->get('secret'));
	}

	/**
	 * @throws Exception
	 */
	public function onRsformFrontendSwitchTasks()
	{
		$app = Factory::getApplication();

		if ($app->input->getString('plugin_task', '') == 'signature.image')
		{
			$hash = $app->input->get('hash');

			if (strlen($hash) == 32)
			{
				// Get the image data
				$db    = Factory::getDbo();
				$query = $db->getQuery(true);
				$query->select($db->qn('FieldValue'))
					->from($db->qn('#__rsform_submission_values'))
					->where('MD5(CONCAT(' . $db->qn('FormId') . ',' . $db->qn('SubmissionId') . ',' . $db->qn('FieldName') . ',' . $db->q(Factory::getConfig()->get('secret')) . ')) = ' . $db->q($hash));
				if ($image = $db->setQuery($query)->loadResult())
				{
					// Display it
					header('Content-Type: image/png');

					echo base64_decode(substr($image, strlen('data:image/png;base64,')));

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

	public function onRsformBackendAfterCreateFieldGroups(&$fieldGroups, $self)
	{
		$fieldGroups['advanced']->fields[] = (object) array(
			'id' 	=> RSFORM_FIELD_SIGNATURE,
			'name' 	=> Text::_('PLG_SYSTEM_RSFPSIGNATURE_LABEL'),
			'icon'  => 'rsficon rsficon-pencil-square'
		);
	}

	/**
	 * Hook to create a new placeholder so you can display the signature {FIELDNAME:signature}
	 *
	 * @param $args
	 */
	public function onRsformAfterCreatePlaceholders($args)
	{
		$formId       = $args['form']->FormId;
		$submission   = &$args['submission'];
		$placeholders = &$args['placeholders'];
		$values       = &$args['values'];

		if ($componentIds = RSFormProHelper::componentExists($formId, $this->componentId))
		{
			$all_data = RSFormProHelper::getComponentProperties($componentIds);

			if ($all_data)
			{
				foreach ($all_data as $data)
				{
					if (!empty($submission->values[$data['NAME']]))
					{
						$url = $this->generateImageLink($formId, $submission->SubmissionId, $data['NAME']);
					}
					else
					{
						$url = '';
					}

					$placeholders[] = '{' . $data['NAME'] . ':signature}';
					$values[]       = !empty($submission->values[$data['NAME']]) ? '<img src="' . RSFormProHelper::htmlEscape($submission->values[$data['NAME']]) . '" />' : '';

					$placeholders[] = '{' . $data['NAME'] . ':signature_image}';
					$values[]       = !empty($submission->values[$data['NAME']]) ? '<img src="' . RSFormProHelper::htmlEscape($url) . '" />' : '';

					$placeholders[] = '{' . $data['NAME'] . ':signature_url}';
					$values[]       = !empty($submission->values[$data['NAME']]) ? $url : '';
				}
			}
		}
	}

	/**
	 * Function to render the signature in the Backend Manage Submission view
	 *
	 * @param $args
	 */
	public function onRsformBackendManageSubmissions($args)
	{
		if ($componentIds = RSFormProHelper::componentExists($args['formId'], $this->componentId))
		{
			$all_data = RSFormProHelper::getComponentProperties($componentIds);

			if ($all_data)
			{
				foreach ($args['submissions'] as $SubmissionId => $submission)
				{
					foreach ($all_data as $data)
					{
						if (isset($args['submissions'][$SubmissionId]['SubmissionValues'][$data['NAME']]['Value']))
						{
							$args['submissions'][$SubmissionId]['SubmissionValues'][$data['NAME']]['Value'] = '<img src="' . RSFormProHelper::htmlEscape($args['submissions'][$SubmissionId]['SubmissionValues'][$data['NAME']]['Value']) . '" class="rsfp-signature-image" />';
						}

					}
				}
			}
		}
	}

	/**
	 * Add the new form field to the unescapedFields array
	 *
	 * @param $args
	 */
	public function onRsformBackendManageSubmissionsCreateUnescapedFields($args)
	{
		if ($componentIds = RSFormProHelper::componentExists($args['formId'], $this->componentId))
		{
			$all_data = RSFormProHelper::getComponentProperties($componentIds);

			if ($all_data)
			{
				foreach ($all_data as $data)
				{
					$args['fields'][] = $data['NAME'];
				}
			}
		}
	}

	/**
	 * @param $field
	 * @param $placeholders
	 */
	public function onRsformBackendManageDirectoriesAfterCreatedPlaceholders($field, &$placeholders)
	{
		if (!empty($field->FieldType) && $field->FieldType == $this->componentId)
		{
			$placeholders['caption'] = '{' . $field->FieldName . ':caption}';
			$placeholders['value']   = '{' . $field->FieldName . ':signature}';
		}
	}

	/**
	 * @param $args
	 */
	public function onRsformBackendManageDirectoriesCreateUnescapedFields($args)
	{
		if ($componentIds = RSFormProHelper::componentExists($args['formId'], $this->componentId))
		{
			$all_data = RSFormProHelper::getComponentProperties($componentIds);

			if ($all_data)
			{
				foreach ($all_data as $data)
				{
					$args['fields'][] = $data['NAME'];
				}
			}
		}
	}

	public function onRsformFrontendInitFormDisplay($args)
	{
		if ($componentIds = RSFormProHelper::componentExists($args['formId'], $this->componentId))
		{
			$all_data = RSFormProHelper::getComponentProperties($componentIds);

			if ($all_data)
			{
				foreach ($all_data as $componentId => $data)
				{
					$args['formLayout'] = preg_replace('/<label (.*?) for="' . preg_quote($data['NAME'], '/') .'"/', '<label $1 for="hidden-rsfpsignature' . $componentId.'"', $args['formLayout']);
				}
			}
		}
	}

	public function onRsformCreateEmailLine($args)
	{
		if ($args['typeId'] == $this->componentId)
		{
			$args['valuePlaceholder'] = str_replace(':value}', ':signature_image}', $args['valuePlaceholder']);
		}
	}

	public function onRsformFrontendGetEditFields(&$return, $submission)
	{
		if ($componentIds = RSFormProHelper::componentExists($submission->FormId, $this->componentId))
		{
			if ($all_data = RSFormProHelper::getComponentProperties($componentIds))
			{
				// Load our field
				require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/fields/rsfpsignature.php';

				// Get values from POST request
				$values = Factory::getApplication()->input->post->get('form', array(), 'array');

				foreach ($all_data as $componentId => $data)
				{
					foreach ($return as $key => $field)
					{
						if (isset($field[RSFORM_DIR_NAME]) && $field[RSFORM_DIR_NAME] == $data['NAME'])
						{
							$config = array(
								'formId' 			=> $submission->FormId,
								'componentId' 		=> $componentId,
								'data' 				=> $data,
								'value' 			=> $values ? $values : $submission->values,
								'invalid' 			=> false,
							);

							$field = new RSFormProFieldRsfpsignature($config);

							$return[$key][RSFORM_DIR_INPUT] = $field->getFormInput();
						}
					}
				}
			}
		}
	}

	public function onRsformBackendGetEditFields(&$return, $submission)
	{
		if ($componentIds = RSFormProHelper::componentExists($submission->FormId, $this->componentId))
		{
			$isPDF = Factory::getApplication()->input->get('format') === 'pdf';
			if ($all_data = RSFormProHelper::getComponentProperties($componentIds))
			{
				foreach ($all_data as $componentId => $data)
				{
					foreach ($return as $key => $field)
					{
						if (isset($field[RSFORM_DIR_NAME]) && $field[RSFORM_DIR_NAME] == $data['NAME'] && !empty($submission->values[$data['NAME']]))
						{
							if ($isPDF)
							{
								$return[$key][RSFORM_DIR_INPUT] = '<img src="' . RSFormProHelper::htmlEscape($submission->values[$data['NAME']]) . '" />';
							}
							else
							{
								$return[$key][RSFORM_DIR_INPUT] = '<img src="' . RSFormProHelper::htmlEscape($submission->values[$data['NAME']]) . '" class="rsfp-signature-image" />' . $field[RSFORM_DIR_INPUT];
							}
						}
					}
				}
			}
		}
	}
}