<?php

/**
 * Snippet to display the submit testimonial 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\testimonials
 * @copyright Copyright (c) 2012 - 2015 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

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

// Passed parameters
$redirectTo = isset($redirectTo) ? $redirectTo : 0;
$editor = isset($editor) ? $editor : '';
$errorClass = isset($errorClass) ? $errorClass : 'testimonialError';

// Get field exclude list (gender,age,occupation,location,email,website,image)
$exclude = isset($exclude) ? explode(',', $exclude) : array();
foreach($exclude as $i => $e)
	$exclude[$i] = trim($e);

// Build the form
$form = new flForm(clearFusionCMS::getRequest(), 'submittestimonialform', $controller->content->getPageURI($controller->pageData['id']), true);

$name = new flFormElementText($form, 'name');
$name->setLabel(__('Your Name', 'testimonials'))
	->setRequired()
	->addValidator(new flFormValidatorRequired())
	->addValidator(new flFormValidatorMaxLength(255));

if(!in_array('gender', $exclude)) {
	$gender = new flFormElementSelect($form, 'gender', null, array('m' => __('Male', 'testimonials'), 'f' => __('Female', 'testimonials')));
	$gender->setLabel(__('Your Gender', 'testimonials'));
}

if(!in_array('age', $exclude)) {
	$age = new flFormElementInteger($form, 'age');
	$age->setLabel(__('Your Age', 'testimonials'));
}

if(!in_array('company', $exclude)) {
	$company = new flFormElementText($form, 'company');
	$company->setLabel(__('Your Company', 'testimonials'))
		->addValidator(new flFormValidatorMaxLength(255));
}

if(!in_array('occupation', $exclude)) {
	$occupation = new flFormElementText($form, 'occupation');
	$occupation->setLabel(__('Your Occupation', 'testimonials'))
		->addValidator(new flFormValidatorMaxLength(255));
}

if(!in_array('location', $exclude)) {
	$location = new flFormElementText($form, 'location');
	$location->setLabel(__('Your Location', 'testimonials'))
		->addValidator(new flFormValidatorMaxLength(255));
}

if(!in_array('email', $exclude)) {
	$email = new flFormElementEmail($form, 'email');
	$email->setLabel('Your Email')
		->addValidator(new flFormValidatorMaxLength(255));
}

if(!in_array('website', $exclude)) {
	$web = new flFormElementUri($form, 'uri');
	$web->setLabel(__('Your Website', 'testimonials'))
		->addValidator(new flFormValidatorMaxLength(255));
}

// Check if changes should be saved before leaving the page
cfConfirm::leavePage($tplEngine);

$ctnt = new flFormElementWYSIWYG($form, 'content');
$ctnt->setLabel(__('Your Testimonial', 'testimonials'))
	->setRequired()
	->addValidator(new flFormValidatorRequired())
	->addValidator(new flFormValidatorMaxLength(2097152))
	->setRows(20)
	->editorSize('100%', '450')
	->setDB(clearFusionCMS::getDb())
	->editorModule($editor);

if(!in_array('image', $exclude)) {
	$fileCfg = clearFusionCMS::getSiteConfig('cfTestimonials');
	$w = $fileCfg->get('lw');
	$h = $fileCfg->get('lh');

	$imgFile = new flFormElementFile($form, 'imgfile');
	$imgFile->setLabel(__('Upload an Image from Your Computer', 'testimonials'))
		->setDescription(sprintf(__('Maximum image size should be %1$d x %2$d pixels.', 'testimonials'), $w, $h));
}

$submit = new flFormElementSubmit($form, 'submittestimonial');
$submit->setCaption(__('Submit Testimonial', 'testimonials'))->setCSS('primary');

// Process the submitted form
$showForm = true;
if($form->isSubmitted() && $form->isValid()) {
	// Create testimonial
	$now = new flDate();
	if(clearFusionCMS::getDb()->insert('cf_testimonials_' . clearFusionCMS::getSite(), array(
		'gender' => isset($gender) ? $gender->getValue() : 'm',
		'age' => isset($age) ? $age->getValue() : '0',
		'dateoftestimonial' => $now->toString(),
		'tags' => '',
		'author' => $name->getValue(),
		'email' => isset($email) ? $email->getValue() : '',
		'location' => isset($location) ? $location->getValue() : '',
		'company' => isset($company) ? $company->getValue() : '',
		'occupation' => isset($occupation) ? $occupation->getValue() : '',
		'website' => isset($web) ? $web->getValue() : '',
		'testimonial' => $ctnt->getCleanedValue(),
		'published' => '0',
		'fileext' => ''
	))) {
		$id = clearFusionCMS::getDb()->insertID();

		if(isset($imgFile)) {
			// If upload file given
			if($imgFile->fileUploaded() && ($fileName = testimonialsBackendController::getFilename($id))) {
				$imgFile->moveTo($fileName);

				// File file present then resize and remember it's extension
				if(is_readable($fileName)) {
					try {
						$img = new flImage($fileName);
						switch($img->getType()) {
							case IMAGETYPE_GIF: $ext = '.gif'; break;
							case IMAGETYPE_JPEG: $ext = '.jpg'; break;
							case IMAGETYPE_PNG: $ext = '.png'; break;
							default: throw new flImageException('Unknown image type.');
						}

						// If image too big scale down
						if($img->getWidth() > ($w * 2) || $img->getHeight() > ($h * 2)) {
							$img->resize($w * 2, $h * 2);
							$img->save();
						}

						clearFusionCMS::getDb()->update('cf_testimonials_' . clearFusionCMS::getSite(), array('fileext' => $ext), 'id=?', $id);
						@rename($fileName, $fileName . $ext);
					} catch(flException $e) {
						@unlink($fileName);
					}
				}
			}
		}

		$fileCfg = clearFusionCMS::getSiteConfig('cfTestimonials');
		if(!empty($fileCfg->notifyEmail)) {
			$mailer = clearFusionCMS::getMailer();
			$mailer->addRecipient($fileCfg->notifyEmail)
				->setSubject(sprintf(__('New testimonial submitted on %s', 'testimonials'), clearFusionCMS::getSiteName()))
				->setTextBody(__("A new testimonial has been submitted to your website.\n\nYou will need to login to your site manager to review and publish it.\n\n", 'testimonials'));

			if($mailer->connect()) {
				$mailer->send();
				$mailer->close();
			}
		}

		$notify = new cfEventNotify(
			clearFusionCMS::getSiteConfig('testimonialsSystemNotify')->get('sub', 3),
			__('New Testimonial', 'testimonials'),
			sprintf(__('A new testimonial has been submitted by: %s', 'testimonials'), $name->getValue())
		);
		$notify->mention(clearFusionCMS::getSiteConfig('testimonialsSystemNotify')->get('mentions', ''))
			->trigger();

		$showForm = false;
		if($redirectTo)
			clearFusionCMS::getResponse()->redirectTo($controller->content->getPageURI($redirectTo, true));
		else
			echo __('Thank you for submitting your testimonial.', 'testimonials');
	}
	else
		echo "<div class=\"$errorClass\">" . __('Something went wrong when submitting your testimonial, please try again.', 'testimonials') . "</div>";
}

if($showForm)
	echo $form->render($tplEngine->getCodeBuffer());
