<?php
/**
* @package RSform!Pro
* @copyright (C) www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// no direct access
defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Pagination\Pagination;

define('RSFORM_FIELD_ZOOM_STATUS', 2008);

class plgSystemRsfpzoom extends CMSPlugin
{
	protected $autoloadLanguage = true;

	public function __construct(&$subject, $config)
	{
		parent::__construct( $subject, $config );

		if (file_exists(JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/zoom_class.php'))
		{
			require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/zoom_class.php';
		}
	}

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

		if ($mappings = $app->input->post->get('zoom_mappings', array(), 'array'))
		{
			foreach ($mappings as $type => $questions)
			{
				$data['zoom_mappings'][$type] = array();
				foreach ($questions as $field_name => $value)
				{
					$data['zoom_mappings'][$type][base64_decode($field_name)] = $value;
				}
			}
		}

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

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

		if ($row = $this->getTable())
		{
			if ($row->load($formId))
			{
				$data = $row->getProperties();
				$data['form_id'] = $newFormId;

				$row->save($data);
			}
		}
	}
	
	public function onRsformFormDelete($formId)
	{
		$db	    = Factory::getDbo();
		$query 	= $db->getQuery(true);

		if ($row = $this->getTable())
		{
			$row->delete($formId);
		}

		// remove the error log for this specific form
		$query->delete('#__rsform_zoom_meetings_error_log')
			->where($db->qn('form_id').'='.$db->q($formId));
		$db->setQuery($query)->execute();
	}

	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('PLG_SYSTEM_RSFPZOOM_LABEL'), 'page-zoom');
		$tabs->addContent($this->configurationScreen());
	}
	
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		?>
		<li><a href="javascript: void(0);" id="rsfpzoom"><span class="rsficon rsficon-zoom"></span><span class="inner-text"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_SETTINGS'); ?></span></a></li>
		<?php
	}
	
	public function onRsformBackendAfterShowFormEditTabs()
	{
		$formId = Factory::getApplication()->input->getInt('formId');
		$db 	= Factory::getDbo();
		$row 	= $this->getTable();

		if (!$row)
		{
			return;
		}

		$row->load($formId);

		// Fields
		$lists = array();
		// Boolean inputs
		$zoom_published 			 = empty($row->zoom_published) ? 0 : 1;
		$zoom_debug 				 = empty($row->zoom_debug) ? 0 : 1;
		$zoom_type 					 = empty($row->zoom_type) ? 'meetings' : 'webinars';
		$lists['debug'] 			 = RSFormProHelper::renderHTML('select.booleanlist', 'zoom[zoom_debug]', '', $zoom_debug);
		$lists['published'] 		 = RSFormProHelper::renderHTML('select.booleanlist', 'zoom[zoom_published]', '', $zoom_published);
		$lists['trigger_on_payment'] = RSFormProHelper::renderHTML('select.booleanlist', 'zoom[zoom_trigger_on_payment]', '', $row->zoom_trigger_on_payment);

		$hasPayment = PluginHelper::isEnabled('system', 'rsfppayment');

		$log = true;

		// check the credentials if they are present
		if (
			empty(RSFormProHelper::getConfig('zoom.accountid')) ||
			empty(RSFormProHelper::getConfig('zoom.clientid')) ||
			empty(RSFormProHelper::getConfig('zoom.clientsecret'))
		)
		{
			// Do not show these errors always, only when the "use" is set to yes
			if ($zoom_published) {
				Factory::getApplication()->enqueueMessage(Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_CREDENTIALS'), 'error');
			}
			$log = false;
		}

		$api = RSFormZoomAPI::getInstance();

		$questions 	 		 = false;
		$mappings 	 		 = array();
		$mw_details 	 	 = array();
		$mw_details_error	 = '';

		$meetingsIds = array('0' => Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_A_MEETING'));
		$webinarsIds = array('0' => Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_A_WEBINAR'));
		$selected_username = Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_USER');

		$languages = array(
				'' 		=> Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_A_LANGUAGE'),
				'site'  => Text::_('PLG_SYSTEM_RSFPZOOM_LANGUAGE_SITE')
		);

		$available_languages = !empty($api->languages) ? $api->languages : array();

		if ($available_languages) {
			foreach ($available_languages as $lang) {
				$lang_t = str_replace('-','_', $lang);
				$lang_t = strtoupper($lang_t);
				$languages[$lang] = Text::_('PLG_SYSTEM_RSFPZOOM_LANGUAGE_'.$lang_t);
			}
		}


		if ($log) {
			// if somehow the saved user does not exist anymore
			if (!empty($row->zoom_user_id))
			{
				// get the selected user the full name fort display purpose
				$details = $api->getUserDetails($formId, $row->zoom_user_id, array('first_name' => '', 'last_name' => ''), true);

				if (!$details)
				{
					$row->zoom_user_id = '0';
				}

				$selected_username = $details ? $details['first_name'].' '.$details['last_name'] : $selected_username;
			}

			if (!empty($row->zoom_user_id)) {
				try {
					if ($zoom_type == 'webinars')
					{
						$webinarsIds = $webinarsIds + $api->getUserWebinars($row->zoom_user_id);
					}
					else
					{
						$meetingsIds = $meetingsIds + $api->getUserMeetings($row->zoom_user_id);
					}
				} catch (Exception $e) {
					$message = $e->getMessage();

					$dataLog = new stdClass();
					$dataLog->form_id = $formId;
					$dataLog->msg = $message;

					$api->storeErrorLog($dataLog);

					Factory::getApplication()->enqueueMessage(Text::sprintf('PLG_SYSTEM_RSFPZOOM_ERROR_GENERAL', $message), 'error');
				}

				// get the questions if there is a meeting ID selected
				if (!empty($row->zoom_meeting_id)) {
					$questions = $api->getQuestions($row->zoom_meeting_id, $formId, $zoom_type);
					try {
						$mw_details = $zoom_type == 'webinars' ? $api->getWebinarDetails($row->zoom_meeting_id) : $api->getMeetingDetails($row->zoom_meeting_id);
						// if for some reason these are not provided
						if (empty($mw_details)) {
							$mw_details_error = $zoom_type == 'webinars' ? Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_WEBINAR_DETAILS') : Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_MEETING_DETAILS');
						}
					} catch(Exception $e) {
						$mw_details_error = $e->getMessage();

						$dataLog = new stdClass();
						$dataLog->form_id = $formId;
						$dataLog->msg = $mw_details_error;
						$api->storeErrorLog($dataLog);
					}

				}
			}
		}
		

		if (!empty($row->zoom_mappings))
		{
			$mappings = unserialize($row->zoom_mappings);
		}

		
		$query 	= $db->getQuery(true);
		$query->select($db->qn('message'))
			  ->select($db->qn('date'))
			  ->from($db->qn('#__rsform_zoom_meetings_error_log'))
			  ->where($db->qn('form_id') . ' = ' . $db->q($formId))
			  ->order($db->qn('date') . ' ' . $db->escape('DESC'));
		$db->setQuery($query, 0, 15);
		$errors = $db->loadObjectList();
		?>
		<div id="rsfpzoomdiv">
			<div class="row-fluid">
				<div>
					<fieldset>
						<h3 class="rsfp-legend"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_SETTINGS_DESC'); ?></h3>
						<div class="alert alert-info">
							<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_DETAILED_DESC'); ?>
						</div>
						<table width="100%" class="table table-bordered">
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_USE_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_USE'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2"><?php echo $lists['published']; ?></td>
							</tr>
							<?php if ($hasPayment) { ?>
								<tr>
									<td width="80" align="right" nowrap="nowrap" class="key">
										<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_TRIGGER_ON_PAYMENT_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_TRIGGER_ON_PAYMENT'); ?></span>
									</td>
									<td nowrap="nowrap" colspan="2"><?php echo $lists['trigger_on_payment']; ?></td>
								</tr>
							<?php } ?>
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_DEBUG_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_DEBUG'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2"><?php echo $lists['debug']; ?></td>
							</tr>

							<?php $current_language = isset($row->zoom_emails_language) ? $row->zoom_emails_language : Factory::getLanguage()->getTag(); ?>
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_EMAILS_LANGUAGE_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_EMAILS_LANGUAGE'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2">
									<?php echo HTMLHelper::_('select.genericlist', $languages, 'zoom[zoom_emails_language]', 'class="form-select"', 'value', 'text', $current_language); ?>
								</td>
							</tr>
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_USER_ID_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_USER_ID'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2">
									<button type="button" class="btn btn-primary" id="zoom_user_full_name" onclick="<?php echo "jQuery('#rsformproZoomUsersModal').modal('show');"; ?>"><?php echo RSFormProHelper::htmlEscape($selected_username); ?></button>
									<button type="button" class="btn btn-danger"<?php echo (empty($row->zoom_user_id) ? ' style="display:none"' : ''); ?> id="zoom_user_reset" onclick="zoomSelectUser('0', '<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_USER')?>')"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_SELECT_USER_RESET'); ?></button>
									<input type="hidden" id="zoom_user_id" name="zoom[zoom_user_id]" value="<?php echo (!empty($row->zoom_user_id) ? $row->zoom_user_id : '0'); ?>"/>
									<?php
									echo HTMLHelper::_('bootstrap.renderModal', 'rsformproZoomUsersModal', array(
										'title' => Text::_('PLG_SYSTEM_RSFPZOOM_SELECT_OR_CHANGE_USER'),
										'url' => Route::_('index.php?option=com_rsform&task=plugin&plugin_task=get_zoom_users&form_id='.$formId.'&limitstart=0&tmpl=component', false),
										'height' => 400,
										'backdrop' => 'static'));
									?>
								</td>
							</tr>
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_TYPE_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_TYPE'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2">
									<?php echo HTMLHelper::_('select.genericlist', array('0'=>Text::_('PLG_SYSTEM_RSFPZOOM_MEETINGS'), '1'=>Text::_('PLG_SYSTEM_RSFPZOOM_WEBINARS')), 'zoom[zoom_type]', 'class="form-select" onchange="zoomShowMeetings(this.value)"', 'value', 'text', isset($row->zoom_type) ? $row->zoom_type : 0); ?>
								</td>
							<tr>
								<td width="80" align="right" nowrap="nowrap" class="key">
									<span class="hasTooltip" title="<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_'.($zoom_type == 'meetings' ? 'MEETING' : 'WEBINAR').'_ID_DESC'); ?>"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_'.($zoom_type == 'meetings' ? 'MEETING' : 'WEBINAR').'_ID'); ?></span>
								</td>
								<td nowrap="nowrap" colspan="2" id="rsf_zoom_meeting_container">
									<?php // if no meetings are found show this alert ?>
									<?php if (($zoom_type == 'meetings' && count($meetingsIds) == 1 ) || ($zoom_type == 'webinars' && count($webinarsIds) == 1 )) { ?>
										<div class="alert alert-error">
											<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_API_ERROR_'.strtoupper($zoom_type).'_NOT_FOUND'); ?>
										</div>
									<?php } else { ?>
										<?php echo HTMLHelper::_('select.genericlist', ($zoom_type == 'meetings' ? $meetingsIds : $webinarsIds), 'zoom[zoom_meeting_id]', 'class="form-select" onchange="zoomShowQuestions()"', 'value', 'text', isset($row->zoom_meeting_id) ? $row->zoom_meeting_id : null); ?>
									<?php } ?>
								</td>
							</tr>
							<tr>
								<td colspan="2" id="rsf_zoom_meeting_details_container"<?php echo ((empty($mw_details) && !strlen($mw_details_error)) ? ' style="display:none"' : ''); ?>>
									<?php if (!empty($mw_details)) { ?>
										<div class="alert alert-info">
											<?php
												if (isset($mw_details['join_url'])) {
													echo Text::_('PLG_SYSTEM_RSFPZOOM_JOIN_URL_PLACEHOLDER');
												}
												if (isset($mw_details['registration_url'])) {
													echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_REGISTRATION_URL_PLACEHOLDER', $mw_details['registration_url'], $mw_details['registration_url']);
												}
												if (isset($mw_details['password'])) {
													echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_PASSWORD_PLACEHOLDER', $mw_details['password']);
												}
												if (isset($mw_details['meeting_id'])) {
													echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_MEETING_ID_PLACEHOLDER', $mw_details['meeting_id']);
												}
											?>
										</div>
									<?php } else { ?>
										<div class="alert alert-danger">
											<?php echo $mw_details_error; ?>
										</div>
									<?php } ?>
								</td>
							</tr>

						</table>
					</fieldset>
					
					<div id="rsf_zoom_questions">
					<?php
					if ($questions) {
						?>
						<table class="table table-bordered"<?php echo !$lists['published'] ? ' style="display: none;"' : ''; ?>>
							<?php $this->outputMappingsTable($questions, $mappings); ?>
						</table>
					<?php } else if (!$questions && $log) { ?>
						<div class="alert alert-error">
							<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_QUESTIONS_FOUND'); ?>
						</div>
					<?php } ?>
					</div>
				</div>

				<div>
					<fieldset>
						<legend><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_FORM_ERROR_LOG'); ?><button type="button" class="btn btn-info pull-right" onclick="zoomClearErrors();"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_CLEAR_ERRORS_BTN'); ?></button></legend>
						<div id="zoom_error_log"<?php echo (!empty($errors) ? ' class="table-responsive"' : ''); ?>>
							<?php if (empty($errors)) { ?>
								<div class="alert alert-error">
									<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_NO_ERRORS_SO_FAR'); ?>
								</div>
							<?php } else { ?>
								<table class="table table-condensed table-bordered">
									<thead>
									<tr>
										<th><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_MESSAGE'); ?></th>
										<th><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_DATETIME'); ?></th>
									</tr>
									</thead>
									<?php foreach ($errors as $error) { ?>
										<tr>
											<td><?php echo RSFormProHelper::htmlEscape($error->message); ?></td>
											<td><?php echo RSFormProHelper::getDate($error->date); ?></td>
										</tr>
									<?php } ?>
								</table>
							<?php } ?>
							</div>
					</fieldset>
				</div>
			</div>
			<script type="text/javascript">
                function zoomSelectUser(user_id, full_name) {
                    jQuery('#zoom_user_id').val(user_id);
                    jQuery('#zoom_user_full_name').text(full_name);

                    // load the meetings
                    var zoom_type = jQuery('[name="zoom[zoom_type]"]').val();
                    zoomShowMeetings(zoom_type);

                    /// hide the modal
                    jQuery('#rsformproZoomUsersModal').modal('hide');
                }

				function zoomShowQuestions() {
					var meeting_id = jQuery('[name="zoom[zoom_meeting_id]"]').val();
					var zoom_type = jQuery('[name="zoom[zoom_type]"]').val();													

					if (meeting_id.trim() == '0') {
						jQuery('#rsf_zoom_questions').empty().append('<div class="alert alert-error"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_QUESTIONS_FOUND'); ?></div>');
						jQuery('#rsf_zoom_meeting_details_container').empty().hide();
						return;
					}

					jQuery.ajax({
						url: 'index.php?option=com_rsform&task=plugin&plugin_task=get_zoom_questions',
						method: "POST",
						data: {meeting_id: meeting_id, form_id: <?php echo $formId; ?>, zoom_type: zoom_type},
						dataType: "json"
					}).done(function (response) {
						var container_questions = jQuery('#rsf_zoom_questions');
						container_questions.html(response.questions);
						container_questions.find('[data-placeholders]').rsplaceholder();

						var container_details = jQuery('#rsf_zoom_meeting_details_container');
						container_details.html(response.details).show();

					});
				}
				function zoomShowMeetings(zoom_type) {
					zoom_type = parseInt(zoom_type);				 
					var user_id = jQuery('[name="zoom[zoom_user_id]"]').val();
					// reset the meetings
					jQuery('#zoom_meeting_id').val(0).trigger('onchange');

					var mw_select_label = jQuery('[name="zoom[zoom_meeting_id]"]').parent().find('.hasTooltip'); 
					if (user_id.trim() == '0') {
						if (zoom_type) {
							jQuery('#rsf_zoom_meeting_container').empty().append('<div class="alert alert-error"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_API_ERROR_WEBINARS_NOT_FOUND'); ?></div>');
						} else {
							jQuery('#rsf_zoom_meeting_container').empty().append('<div class="alert alert-error"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_API_ERROR_MEETINGS_NOT_FOUND'); ?></div>');
						}

						jQuery('#rsf_zoom_questions').empty().append('<div class="alert alert-error"><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_QUESTIONS_FOUND'); ?></div>');
						jQuery('#rsf_zoom_meeting_details_container').empty().hide();
						return;
					}

					if (zoom_type) {
						mw_select_label.attr('title', '<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_WEBINAR_ID_DESC'); ?>');
						mw_select_label.html('<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_WEBINAR_ID'); ?>');
					} else {
						mw_select_label.attr('title', '<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_MEETING_ID_DESC'); ?>');
						mw_select_label.html('<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_MEETING_ID'); ?>');
					}
					
					jQuery.ajax({
						url: 'index.php?option=com_rsform&task=plugin&plugin_task=get_zoom_mw',
						method: "POST",
						data: {user_id: user_id, form_id: <?php echo $formId; ?>, zoom_type: zoom_type},
						dataType: "html"
					}).done(function (response) {
						var container = jQuery('#rsf_zoom_meeting_container');
						container.html(response);

						// check to see if any selection is stored in the database, and is selected of course
						var selected_meeting = container.find('[name="zoom[zoom_meeting_id]"]');
						if (selected_meeting && selected_meeting.val()) {
							zoomShowQuestions();
						}
					});
				}

				function zoomClearErrors() {
					var confirmed = confirm('<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_CLEAR_ERRORS_CONFIRM'); ?>');

					if (confirmed) {
						jQuery.ajax({
							url: 'index.php?option=com_rsform&task=plugin&plugin_task=clear_zoom_errors',
							method: "POST",
							data: {form_id: <?php echo $formId; ?>},
							dataType: "html"
						}).done(function (response) {
							if (response == '') {
								alert('<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_GENERAL_ERROR'); ?>');
							} else {
								jQuery('#zoom_error_log').html(response);
							}
						});
					}
				}
			</script>
		</div>
		<?php
	}

	private function outputMappingsTable($questions, $mappings) {
		$type = '';
		foreach($questions as $i => $question) {
			if ($type != $question['type']) {
				// if the type has changed assign the now one
				$type = $question['type'];
				?>
				<tr>
					<td colspan="2"><h4><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_QUESTIONS_TYPE_'.strtoupper($type)); ?></h4></td>
				</tr>
				<?php
			}
			?>
			<tr>
				<td width="80" align="right" nowrap="nowrap" class="key">
					<?php
					if ($type == 'custom_question') {
						echo RSFormProHelper::htmlEscape($question['question']).($question['required'] ? ' *' : '');
					} else {
						echo Text::_('PLG_SYSTEM_RSFPZOOM_QUESTIONS_FIELD_'.strtoupper(RSFormProHelper::htmlEscape($question['question']))).($question['required'] ? ' *' : '');
					}
					?>
				</td>
				<td>
					<input name="zoom_mappings[<?php echo $type; ?>][<?php echo base64_encode($question['question']); ?>]" style="width: 80%;" id="zoom_mappings_<?php echo $i; ?>"  value="<?php echo (isset($mappings[$type][$question['question']]) ? RSFormProHelper::htmlEscape($mappings[$type][$question['question']]) : ''); ?>" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
					<?php
					if (!empty($question['answers'])) {
						// break if this is array (multiple answers)
						if (is_array($question['answers'])) {
							$question['answers'] = implode("<br/>", $question['answers']);
						}
						echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_POSSSIBLE_ANSWERS_DESC', $question['answers']);
					}
					?>
				</td>
			</tr>
		<?php
		}
	}

	private function configurationScreen()
	{
		ob_start();

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

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

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

		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;
	}

	private function loadFormData()
	{
		$data 	= array();
		$db 	= Factory::getDbo();

		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn('#__rsform_config'))
			->where($db->qn('SettingName') . ' LIKE ' . $db->q('zoom.%', false).' OR '.$db->qn('SettingName').' = '.$db->q('zoom_type'));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}
	
	public function onRsformBackendSwitchTasks()
	{
		$app 			= Factory::getApplication();
		$input 			= $app->input;
		$plugin_task 	= $input->getCmd('plugin_task','');
		
		switch ($plugin_task)
		{
			// get all users
			case 'get_zoom_users':
				$formId = $input->getString('form_id', '');
				$limitstart = $input->getInt('limitstart', 0);
				$limit = (int) RSFormProHelper::getConfig('zoom.pagesize');


				if (empty($formId)) {
					$app->close();
				}

				HTMLHelper::_('behavior.core');

				// build the page for the call
				$page = $limitstart > 0 ? (floor($limitstart / $limit) + 1 ) : 1;

				$api 		= RSFormZoomAPI::getInstance();
				$list = $api->getUsersList($formId, array('page_number'=> $page), true);

				if (!empty($list))
				{
					$pagination = new Pagination($list['total_records'], $limitstart, $limit);

					?>
					<form method="post" name="adminForm" id="adminForm" action="index.php">
						<table class="table table-bordered">
							<tr>
								<th><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_QUESTIONS_FIELD_FIRST_NAME');?></th>
								<th><?php echo Text::_('PLG_SYSTEM_RSFPZOOM_QUESTIONS_FIELD_LAST_NAME');?></th>
							</tr>
							<?php foreach ($list['users'] as $user) { ?>
								<tr>
									<td>
										<?php echo $user['first_name']; ?>
									</td>
									<td>
										<?php echo $user['last_name']; ?>
									</td>
									<td class="center">
										<button type="button" class="btn btn-success" onclick="parent.zoomSelectUser('<?php echo RSFormProHelper::htmlEscape($user['id']); ?>', '<?php echo RSFormProHelper::htmlEscape($user['first_name']).' '.RSFormProHelper::htmlEscape($user['last_name']); ?>')">Select</button>
									</td>
								</tr>
							<?php } ?>
						</table>
						<?php echo $pagination->getListFooter(); ?>
						<input type="hidden" name="option" value="com_rsform"/>
						<input type="hidden" name="task" value="plugin"/>
						<input type="hidden" name="plugin_task" value="get_zoom_users"/>
						<input type="hidden" name="tmpl" value="component"/>
						<input type="hidden" name="form_id" value="<?php echo $formId; ?>"/>
					</form>
					<?php
				}
				break;

			// clear all errors
			case 'clear_zoom_errors':
				$formId = $input->getString('form_id', '');

				if (empty($formId)) {
					$app->close();
				}

				$api = RSFormZoomAPI::getInstance();
				$api->deleteAllErrorLog($formId);

				?>
					<div class="alert alert-error">
						<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_NO_ERRORS_SO_FAR'); ?>
					</div>
				<?php

				$app->close();
			break;

			// get the questions regarding this meeting
			case 'get_zoom_questions':
				$meeting_id = $input->getString('meeting_id', '');
				$formId = $input->getString('form_id', '');
				$zoom_type = $input->getString('zoom_type', '');
				$zoom_type = empty($zoom_type) ? 'meetings' : 'webinars';										 

				$api 		= RSFormZoomAPI::getInstance();
				
				$questions = $api->getQuestions($meeting_id, $formId, $zoom_type);

				$row 	= $this->getTable();

				if (!$row)
				{
					$app->close();
				}

				$row->load($formId);

				$mappings = array();
				if (!empty($row->zoom_mappings))
				{
					$mappings = unserialize($row->zoom_mappings);
				}

				ob_start();
				if ($questions) {
					?>
					<table class="table table-bordered">
						<?php $this->outputMappingsTable($questions, $mappings); ?>
					</table>

				<?php
				}
				else
				{
					?>
					<div class="alert alert-error">
						<?php echo Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_QUESTIONS_FOUND'); ?>
					</div>
					<?php
				}
				$questions_content = ob_get_contents();
				ob_end_clean();


				// Handle details
				$mw_details 	 	 = array();
				$mw_details_error	 = '';
				try {
					$mw_details = $zoom_type == 'webinars' ? $api->getWebinarDetails($meeting_id) : $api->getMeetingDetails($meeting_id);
					// if for some reason these are not provided
					if (empty($mw_details)) {
						$mw_details_error = Text::_('PLG_SYSTEM_RSFPZOOM_ERROR_NO_MEETING_DETAILS');
					}
				} catch(Exception $e) {
					$mw_details_error = $e->getMessage();

					$dataLog = new stdClass();
					$dataLog->form_id = $formId;
					$dataLog->msg = $mw_details_error;
					$api->storeErrorLog($dataLog);
				}

				ob_start();
				if (!empty($mw_details)) { ?>
					<div class="alert alert-info">
						<?php
						if (isset($mw_details['join_url'])) {
							echo Text::_('PLG_SYSTEM_RSFPZOOM_JOIN_URL_PLACEHOLDER');
						}
						if (isset($mw_details['registration_url'])) {
							echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_REGISTRATION_URL_PLACEHOLDER', $mw_details['registration_url'], $mw_details['registration_url']);
						}
						if (isset($mw_details['password'])) {
							echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_PASSWORD_PLACEHOLDER', $mw_details['password']);
						}
						if (isset($mw_details['meeting_id'])) {
							echo Text::sprintf('PLG_SYSTEM_RSFPZOOM_MEETING_ID_PLACEHOLDER', $mw_details['meeting_id']);
						}
						?>
					</div>
				<?php } else { ?>
					<div class="alert alert-danger">
						<?php echo $mw_details_error; ?>
					</div>
				<?php }

				$details_content = ob_get_contents();
				ob_end_clean();

				Factory::getDocument()->setMimeEncoding('application/json');
				$data = (object) array('questions' => $questions_content, 'details' => $details_content);

				echo json_encode($data);

				$app->close();
			break;

			// Get the available meetings for the selected user
			case 'get_zoom_mw':
				
				$user_id = $input->getString('user_id', '');
				$formId = $input->getString('form_id', '');
				$zoom_type = $input->getString('zoom_type', '');
				$zoom_type = empty($zoom_type) ? 'meetings' : 'webinars';									 

				$api 		= RSFormZoomAPI::getInstance();

				$row 	= $this->getTable();

				if (!$row)
				{
					$app->close();
				}

				$row->load($formId);

				$meetingsIds = array('0' => Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_A_MEETING'));
				$webinarsIds = array('0' => Text::_('PLG_SYSTEM_RSFPZOOM_PLEASE_SELECT_A_WEBINAR'));			  
				$error_found = '';
				try {
					if ($zoom_type == 'webinars')
					{
						$webinarsIds = $webinarsIds + $api->getUserWebinars($user_id);
					}
					else
					{
						$meetingsIds = $meetingsIds + $api->getUserMeetings($user_id);
					}
				} catch (Exception $e) {
					$dataLog = new stdClass();
					$dataLog->form_id = $formId;
					$dataLog->msg = $e->getMessage();
					$error_found = $dataLog->msg;

					$api->storeErrorLog($dataLog);
				}

				// if no meetings are found show this alert
				if (($zoom_type == 'meetings' && count($meetingsIds) == 1) || ($zoom_type == 'webinars' && count($webinarsIds) == 1)) { ?>
					<div class="alert alert-error">
						<?php echo $error_found; ?>
					</div>
				<?php } else {
					echo HTMLHelper::_('select.genericlist', ($zoom_type == 'meetings' ? $meetingsIds: $webinarsIds), 'zoom[zoom_meeting_id]', 'class="form-select" onchange="zoomShowQuestions()"', 'value', 'text', isset($row->zoom_meeting_id) ? $row->zoom_meeting_id : null);
				}

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

	private function getSettings($formId)
	{
		static $cache = array();

		if (!isset($cache[$formId]))
		{
			$row = $this->getTable();
			if ($row->load($formId) && $row->zoom_published)
			{
				$cache[$formId] = $row;
			}
			else
			{
				$cache[$formId] = false;
			}
		}

		if (!empty($cache[$formId]))
		{
			return clone $cache[$formId];
		}

		return false;
	}

	public function onRsformAfterConfirmPayment($SubmissionId)
	{
		require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/submissions.php';
		$submission = RSFormProSubmissionsHelper::getSubmission($SubmissionId, false);

		if ($submission)
		{
			if ($row = $this->getSettings($submission->FormId))
			{
				if ($row->zoom_trigger_on_payment)
				{
					$this->addRegistrant($submission->FormId, $SubmissionId, $row);
				}
			}
		}
	}

	/*
	* Functions used only inside this class
	*/
	public function onRsformFrontendAfterStoreSubmissions($args)
	{
		$formId 		= (int) $args['formId'];
		$SubmissionId 	= (int) $args['SubmissionId'];

		if ($row = $this->getSettings($formId))
		{
			if (empty($row->zoom_trigger_on_payment) || $this->_getTotal($SubmissionId) === '0.00')
			{
				$this->addRegistrant($formId, $SubmissionId, $row);
			}
		}
	}

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

		if ($row = $this->getSettings($formId))
		{
			if (!empty($row->zoom_published))
			{
				$args['post']['_ZOOM_JOIN_URL'] = '';
				$args['post']['_ZOOM_STATUS'] = '0';
			}
		}
	}

	public function onRsformBackendGetSubmissionHeaders(&$headers, $formId)
	{
		if ($row = $this->getSettings($formId))
		{
			$headers[] = '_ZOOM_STATUS';
		}
	}

	public function onRsformBackendGetHeaderLabel(&$header, $formId)
	{
		if ($row = $this->getSettings($formId))
		{
			if ($header === '_ZOOM_STATUS')
			{
				$header = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS');
			}
		}
	}

	public function onRsformFrontendGetEditFields(&$return, $submission)
	{
		if ($row = $this->getSettings($submission->FormId))
		{
			if (isset($submission->values['_ZOOM_STATUS']) && isset($return[-RSFORM_FIELD_ZOOM_STATUS]))
			{
				$name   = '_ZOOM_STATUS';
				$value  = $submission->values['_ZOOM_STATUS'];

				$return[-RSFORM_FIELD_ZOOM_STATUS][0] = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS');

				if (Factory::getApplication()->input->get('format') == 'pdf')
				{
					$return[-RSFORM_FIELD_ZOOM_STATUS][1] = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_' . $value);
				}
				else
				{
					$options = array(
						HTMLHelper::_('select.option', 0, Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_0')),
						HTMLHelper::_('select.option', 1, Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_1'))
					);
					$return[-RSFORM_FIELD_ZOOM_STATUS][1] = HTMLHelper::_('select.genericlist', $options, 'form['.$name.'][]', null, 'value', 'text', $value);
				}
			}
		}
	}

	public function onRsformBackendGetEditFields(&$return, $submission)
	{
		if ($row = $this->getSettings($submission->FormId))
		{
			if (isset($submission->values['_ZOOM_STATUS']))
			{
				$name   = '_ZOOM_STATUS';
				$value  = $submission->values['_ZOOM_STATUS'];

				$new_field[0] = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS');

				if (Factory::getApplication()->input->get('format') == 'pdf')
				{
					$new_field[1] = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_' . $value);
				}
				else
				{
					$options = array(
						HTMLHelper::_('select.option', 0, Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_0')),
						HTMLHelper::_('select.option', 1, Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_1'))
					);
					$new_field[1] = HTMLHelper::_('select.genericlist', $options, 'form['.$name.'][]', null, 'value', 'text', $value);
				}

				$return[] = $new_field;
			}
		}
	}

	public function onRsformBackendManageSubmissions($args)
	{
		if ($row = $this->getSettings($args['formId']))
		{
			foreach ($args['submissions'] as $SubmissionId => $submission)
			{
				if (isset($submission['SubmissionValues']['_ZOOM_STATUS']['Value']))
				{
					$args['submissions'][$SubmissionId]['SubmissionValues']['_ZOOM_STATUS']['Value'] = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_' . $submission['SubmissionValues']['_ZOOM_STATUS']['Value']);
				}
			}
		}
	}

	public function onRsformBackendGetAllDirectoryFields(&$cache, $formId)
	{
		if ($row = $this->getSettings($formId))
		{
			$cache[-RSFORM_FIELD_ZOOM_STATUS] = (object)array(
				'FieldName' => '_ZOOM_STATUS',
				'FieldId' => -RSFORM_FIELD_ZOOM_STATUS,
				'FieldType' => 0,
				'FieldCaption' => Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS')
			);
		}
	}

	public function onRsformAfterManageDirectoriesQuery(&$items, $formId)
	{
		if ($row = $this->getSettings($formId))
		{
			if (!empty($row->zoom_published))
			{
				foreach ($items as $item)
				{
					if (isset($item->{'_ZOOM_STATUS'})) {
						$item->{'_ZOOM_STATUS'} = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_' . $item->{'_ZOOM_STATUS'});
					}
				}
			}
		}
	}

	private function addRegistrant($formId, $SubmissionId, $row){
		list($replace, $with) = RSFormProHelper::getReplacements($SubmissionId);
		$replace[] = '\n';
		$with[] = "\n";

		if (empty($row->zoom_mappings))
		{
			return;
		}

		if (empty($row->zoom_user_id))
		{
			return;
		}

		if (empty($row->zoom_meeting_id))
		{
			return;
		}

		$data = @unserialize($row->zoom_mappings);
		if (!is_array($data))
		{
			$data = array();
		}

		foreach ($data as $type => $questions)
		{
			foreach ($questions as $field_name => $value) {
				$value = str_replace($replace, $with, $value);
				if ($type == 'custom_question') {
					// start the custom question array (these must be grouped in an array, unlike the other field/questions, and at plural)
					if (!isset($data['custom_questions'])) {
						$data['custom_questions'] = array();
					}
					$data['custom_questions'][] = (object) array('title' => $field_name, 'value' => $value);
				} else {
					$data[$field_name] = str_replace($replace, $with, $value);
				}
			}
		}

		$zoom_type = $row->zoom_type == '1' ? 'webinars' : 'meetings';		
		$api = RSFormZoomAPI::getInstance();

		try {
			// if there are differences between the mapping and the actual questions in the Registration questions, populate only the ones that match
			$questions = $api->getQuestions($row->zoom_meeting_id, $formId, $zoom_type);

			// if no questions found for this meeting skip the add
			if (empty($questions)) {
				return;
			}

			$question_fields = array();
			$custom_question_fields = array();

			// separate other question from the custom ones so that we will not do this for every field
			foreach ($questions as $question) {
				if ($question['type'] == 'custom_question') {
					$custom_question_fields[] = $question['question'];
				} else {
					$question_fields[] = $question['question'];
				}
			}

			// remove the unused qustions from the data
			foreach ($data as $field_name => $value) {
				if ($field_name == 'custom_questions' && is_array($value)) {
					foreach ($value as $j => $c_value) {
						if (!in_array($c_value->title, $custom_question_fields))
							unset($data['custom_questions'][$j]);
					}
				} else {
					if (!in_array($field_name, $question_fields)) {
						unset($data[$field_name]);
					}
				}
			}

			// set the selected language for the emails
			if (!empty($row->zoom_emails_language))
			{
				if ($row->zoom_emails_language == 'site')
				{
					$current_lang = Factory::getLanguage()->getTag();
					$available_languages = !empty($api->languages) ? $api->languages : array();

					if (in_array($current_lang, $available_languages))
					{
						// if the site language is a zoom available language use it
						$data['language'] = $current_lang;
					}
					else
					{
						// if there is not a full match try to find a best match
						list($our_lang, $tmp) = explode('-', $current_lang);

						foreach ($available_languages as $lang)
						{
							list($api_lang, $tmp) = explode('-', $lang);

							if ($api_lang == $our_lang)
							{
								$data['language'] = $lang;
								break;
							}
						}
					}
				}
				else
				{
					$data['language'] = $row->zoom_emails_language;
				}
			}

			// add the type (meeting/webinar) to the data
			$data['zoom_type'] = $zoom_type;			   
			$join_url = $api->addRegistrant($row->zoom_meeting_id, $data);

			// update in submissions the status
			$db    = Factory::getDBO();
			$query = $db->getQuery(true);
			$query->clear()
				->update($db->qn('#__rsform_submission_values'))
				->set($db->qn('FieldValue') . ' = ' . $db->q('1'))
				->where($db->qn('FieldName') . '=' . $db->q('_ZOOM_STATUS'))
				->where($db->qn('SubmissionId') . '=' . $db->q($SubmissionId));
			$db->setQuery($query);
			$db->execute();

			if (!is_null($join_url)) {
				// update in submissions the join url
				$query = $db->getQuery(true);
				$query->clear()
					->update($db->qn('#__rsform_submission_values'))
					->set($db->qn('FieldValue') . ' = ' . $db->q($join_url))
					->where($db->qn('FieldName') . '=' . $db->q('_ZOOM_JOIN_URL'))
					->where($db->qn('SubmissionId') . '=' . $db->q($SubmissionId));
				$db->setQuery($query);
				$db->execute();
			}
		} catch (Exception $e) {
			$dataLog = new stdClass();
			$dataLog->form_id = $formId;
			$dataLog->msg = $e->getMessage();

			// if debug is active
			if ($row->zoom_debug) {
				Factory::getApplication()->enqueueMessage(Text::sprintf('PLG_SYSTEM_RSFPZOOM_ERROR_GENERAL', $dataLog->msg), 'warning');
			}

			$api->storeErrorLog($dataLog);
		}
	}

	public function onRsformAfterCreatePlaceholders($args) {
		$formId = $args['form']->FormId;

		if ($row = $this->getSettings($formId))
		{
			if (!empty($row->zoom_meeting_id))
			{
				$api 		= RSFormZoomAPI::getInstance();
				$zoom_type 	= empty($row->zoom_type) ? 'meetings' : 'webinars';												   
				try {
					$mw_details = $zoom_type == 'webinars' ? $api->getWebinarDetails($row->zoom_meeting_id) : $api->getMeetingDetails($row->zoom_meeting_id);

					// if there is an join_url lets use it
					$args['placeholders'][] = '{zoom_join_url}';
					$args['values'][] 		= isset($args['submission']->values['_ZOOM_JOIN_URL']) ? $args['submission']->values['_ZOOM_JOIN_URL'] : '';

					// password placeholder
					$args['placeholders'][] = '{zoom_password}';
					$args['values'][] 		= !empty($mw_details['password']) ? $mw_details['password']: '';

					// registration url placeholder
					$args['placeholders'][] = '{zoom_registration_url}';
					$args['values'][] 		= !empty($mw_details['registration_url']) ? $mw_details['registration_url']: '';

					// meeting_id
					$args['placeholders'][] = '{zoom_meeting_id}';
					$args['values'][] 		= !empty($mw_details['meeting_id']) ? $mw_details['meeting_id']: '';
				} catch(Exception $e) {
					$dataLog = new stdClass();
					$dataLog->form_id = $formId;
					$dataLog->msg =  $e->getMessage();
					$api->storeErrorLog($dataLog);
				}
			}

			$args['placeholders'][] = '{_ZOOM_STATUS:value}';
			$args['values'][]       = isset($args['submission']->values['_ZOOM_STATUS']) ? Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS_' . $args['submission']->values['_ZOOM_STATUS']) : '';

			$args['placeholders'][] = '{_ZOOM_STATUS:caption}';
			$args['values'][]       = Text::_('PLG_SYSTEM_RSFPZOOM_ZOOM_STATUS');
		}
	}

	public function onRsformAfterCreateQuickAddGlobalPlaceholders(& $placeholders, $type)
	{
		if ($type === 'display')
		{
			$placeholders[] = '{zoom_join_url}';
			$placeholders[] = '{zoom_password}';
			$placeholders[] = '{zoom_registration_url}';
			$placeholders[] = '{zoom_meeting_id}';
			$placeholders[] = '{_ZOOM_STATUS:caption}';
			$placeholders[] = '{_ZOOM_STATUS:value}';
		}
	}

	/*
	* End Functions used only inside this class
	*/
	public function onRsformFormBackup($form, $xml, $fields)
	{
		$db 	= Factory::getDbo();
		$query 	= $db->getQuery(true);
		$query->select('*')
			  ->from($db->qn('#__rsform_zoom_meetings'))
			  ->where($db->qn('form_id').'='.$db->q($form->FormId));
		$db->setQuery($query);
		if ($zoom = $db->loadObject())
		{
			// No need for a form_id
			unset($zoom->form_id);
			
			$xml->add('zoom');
			foreach ($zoom as $property => $value)
			{
				$xml->add($property, $value);
			}
			$xml->add('/zoom');
		}
		
		// export the error log
		$query 	= $db->getQuery(true);
		$query->select('*')
			  ->from($db->qn('#__rsform_zoom_meetings_error_log'))
			  ->where($db->qn('form_id').'='.$db->q($form->FormId));
		$db->setQuery($query);
		if ($errors = $db->loadObjectList())
		{
			$xml->add('zoomlog');
			foreach ($errors as $error)
			{
				// No need for a form_id
				unset($error->form_id);
				unset($error->id);
				
				$xml->add('error');
				foreach ($error as $property => $value)
				{
					$xml->add($property, $value);
				}
				$xml->add('/error');
			}
			$xml->add('/zoomlog');
		}
	}
	
	public function onRsformFormRestore($form, $xml, $fields)
	{
		$db = Factory::getDbo();

		if (isset($xml->zoom))
		{
			$data = array(
				'form_id' => $form->FormId
			);
			
			foreach ($xml->zoom->children() as $property => $value)
			{
				$data[$property] = (string) $value;
			}
			
			$row = $this->getTable();
			$row->save($data);
		}
		
		// the error log
		if (isset($xml->zoomlog))
		{
			foreach ($xml->zoomlog->error  as $error)
			{
				$data = array(
					$db->qn('form_id') .'='. $db->q($form->FormId)
				);
				
				foreach ($error->children() as $property => $value)
				{
					$value = (string) $value;
					$data[] = $db->qn($property) .'='. $db->q($value);
				}
				
				$db = Factory::getDbo();
				$query = $db->getQuery(true);
				$query	->insert('#__rsform_zoom_meetings_error_log')
						->set($data);
				$db->setQuery($query)->execute();
			}
		}
	}

	protected function _getTotal($submissionId)
	{
		$db = Factory::getDbo();
		$query = $db->getQuery(true)
			->select($db->qn('FieldValue'))
			->from($db->qn('#__rsform_submission_values'))
			->where($db->qn('SubmissionId') . ' = ' . $db->q($submissionId))
			->where($db->qn('FieldName') . ' = ' . $db->q('rsfp_Total'));
		$db->setQuery($query);
		return $db->loadResult();
	}
}