<?php

/**
 * Snippet to display and process a form.
 *
* THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
 * @package clearFusionCMS\module\forms
 * @copyright Copyright (c) 2012 - 2016 clearFusionCMS. All rights reserved.
* @link http://clearfusioncms.com
*/

/* @var $tplEngine cfTemplateEngine */
$controller = $tplEngine->controller;

if(isset($id) && $data = clearFusionCMS::getDb()->fetchRow('SELECT formid,submitdelay,storeemails,displayname,subject,recipient,mentions,intro,thankyou,htmlemail,textemail,formdata FROM cf_forms WHERE formid=?', $id)) {
	$useUL = isset($useUL) && $useUL;

	// Create the form
	$form = new flForm(clearFusionCMS::getRequest(), 'form' . $data['formid'], $controller->getRequest()->getSelf(), true, null, $useUL ? new flFormDecoratorList(new flFormDecoratorUl()) : null, $useUL ? new flFormDecoratorList(new flFormDecoratorLi()) : null);

	if(isset($requiredText))
		$form->setRequiredText($requiredText);

	// Get system reCAPTCHA keys
	$cfg = clearFusionCMS::getSiteConfig('cfSystemSocialAPI');
	$options = array(
		'recaptcha_sitekey' => $cfg->get('recaptcha_sitekey'),
		'recaptcha_secretkey' => $cfg->get('recaptcha_secretkey')
	);

	$cfgForms = clearFusionCMS::getSiteConfig('formsSystemEdit');

	$builder = new flFormBuilder();
	if($builder->build($form, $data['formdata'], $_params, clearFusionCMS::getSession()->getNamespace('forms.use.Verify.' . $data['formid']), $options)) {
		$hideform = false;

		// If submission delay enabled test if delay met
		$canSubmit = true;
		if($data['submitdelay']) {
			$now = new flDate();
			$start = clearFusionCMS::getSession()->flashGet('cfFormsDelay' . $data['formid'], $now);
			clearFusionCMS::getSession()->flashSet('cfFormsDelay' . $data['formid'], $start);
			$canSubmit = ($now->getTimestamp() - $start->getTimestamp()) > $data['submitdelay'];
		}

		// If form submitted then build and send the email
		if($form->isSubmitted() && $form->isValid()) {

			if($canSubmit) {
				// Process the HTML and text email bodies
				$tplEngine = new cfTemplateEngine($controller);

				if($cfgForms->get('emailFilter')) {
					$html = $tplEngine->runSnippet($cfgForms->get('emailFilter'), array(
						'content' => $data['htmlemail']
					));
				}
				else
					$html = $data['htmlemail'];

				$html = $tplEngine->parseString("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\" />\n</head>\n<body>\n" . $html . "\n</body>\n</html>\n", $builder->getData(true));
				$text = $tplEngine->parseString($data['textemail'], $d = $builder->getData());

				// Parse the XML & get the replyto field
				$replyto = $replyName = '';
				$definition = @simplexml_load_string($data['formdata']);
				if($definition && isset($definition->replyto)) {
					$attrs = $definition->replyto->attributes();
					if(isset($attrs['field']) && isset($d[(string)$attrs['field']])) {
						$replyto = $d[(string)$attrs['field']];
						$replyName = (isset($attrs['name']) && isset($d[(string)$attrs['name']]) ? $d[(string)$attrs['name']] : '');
					}
				}

				// Store emails to database if required
				if($data['storeemails']) {
					$now = new flDate();
					clearFusionCMS::getDb()->insert('cf_formssent', array(
						'formid' => $data['formid'],
						'sentat' => $now->toString(),
						'email' => "$replyName <$replyto>",
						'msg' => serialize(array('content' => $text, 'data' => $d))
					));
				}

				// Send the email
				$mailer = clearFusionCMS::getMailer();
				if($mailer->connect()) {
					$mailer
						->setTextBody($text)
						->setHTMLBody($html)
						->setSubject($tplEngine->parseString($data['subject'], $d))
						->replyTo($replyto, $replyName);

					$addrs = explode(',', $data['recipient']);
					foreach($addrs as $recip)
						$mailer->addRecipient($recip);

					// Attach any files
					$files = $builder->getFileData();
					foreach($files as $n => $f)
						$mailer->attachFile($f->getTmpFileName(), null, $f->getFileName());

					// Send the message
					if($r = $mailer->send())
						$hideform = true;

					$mailer->close();

					if($r) {
						$notify = new cfEventNotify(
							clearFusionCMS::getSiteConfig('formsSystemNotify')->get('submission', 3),
							__('New Form Submission', 'forms'),
							$data['subject'] . " \n" . $text
						);
						$notify->mention(empty($data['mentions']) ? '' : $data['mentions'])
							->trigger();

						if(isset($redirectTo))
							clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($redirectTo, true));
						else {
							if($cfgForms->get('htmlFilter')) {
								echo $tplEngine->runSnippet($cfgForms->get('htmlFilter'), array(
									'content' => $data['thankyou']
								));
							}
							else
								echo $data['thankyou'];
						}
					}
					else
						echo __('<p class="formError">An error has occurred, please try again.</p>', 'forms');
				}
				else
					echo __('<p class="formError">An error has occurred, please try again.</p>', 'forms');
			}
			else
				echo __('<p class="formError">As part of our anti-spam measures we limit how fast you can complete and submit the form. You managed to complete the form quicker than expected therefore please wait a few seconds and try submitting the form again. We are sorry for the inconvenience caused.</p>', 'forms');
		}

		if(!$hideform) {
			if($cfgForms->get('htmlFilter')) {
				$intro = $tplEngine->runSnippet($cfgForms->get('htmlFilter'), array(
					'content' => $data['intro']
				));
			}
			else
				$intro = $data['intro'];

			echo $intro . $form->render($tplEngine->getCodeBuffer());
		}
	}
}
