<?php
namespace SGalinski\SgMail\Service;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Lang\LanguageService;
use Typoheads\Formhandler\Finisher\AbstractFinisher;

/***************************************************************
 *  Copyright notice
 *
 *  (c) sgalinski Internet Services (https://www.sgalinski.de)
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

/**
 * Class FormhandlerFinisherService
 *
 * @package SGalinski\SgMail\Service
 */
class FormhandlerFinisherService extends AbstractFinisher {

	/**
	 * Hook into Formhandler, sets config and form input
	 * gets called in the finisher of the typoscript
	 * redirects to process() function
	 *
	 * @param array $formInput
	 * @param array $settings
	 */
	public function init($formInput, $settings) {
		$this->gp = $formInput;
		foreach ($formInput as &$userInput) {
			GeneralUtility::removeXSS($userInput);
		}

		$this->settings = $settings;
	}

	/**
	 *  Redirect Formhandler input to send Email Function
	 *  Needed to hook into Formhandler
	 *
	 * @return array $gp
	 */
	public function process() {
		/** @var $translator LanguageService */
		$translator = (TYPO3_MODE === 'FE' ? $GLOBALS['TSFE'] : $GLOBALS['LANG']);
		$subject = $translator->sL($this->settings['subject'], TRUE);

		$toAddress = $this->settings['to_address'];
		if ($toAddress === 'email') {
			$toAddress = $this->gp['email'];
		}

		$language = $GLOBALS['TSFE']->config['config']['language'];
		$fromAddress = [$this->settings['from_address'] => $this->settings['from_name']];

		MailTemplateService::sendEmail(
			$language, $this->settings['template_key'], $this->settings['extension_key'], $toAddress,
			$fromAddress, $subject, $this->gp,
			$this->settings['ignore_mail_queue']
		);
		return $this->gp;
	}

	/**
	 * Needed to hook into Formhandler
	 * simply returns true
	 */
	public function validateConfig() {
		parent::validateConfig();
	}

}