<?php

namespace App\Config;

class AutoEmailSender extends XmlBasicAbstract
{

	/**
	 * Stores the configuration file (relative to the "files/config/" dir). For config files stored
	 * inside subdirectories, the subdirectory is included (Ex: services/servicesList.xml).
	 * @var String
	 */
	protected $fileName=CONFIG_FILE_AUTOEMAILSENDER;

	/**
	 * The types of email senders.
	 * @var array
	 */
	private $senderTypes = ['securityIssues', 'calendarEvents', 'cronJobs', 'reports', 'collectionReminders', 'FluX', 'invoice', 'cashing'];

	/**
	 * (non-PHPdoc)
	 * @see \App\Config\XmlBasicAbstract::getAll_rawData_extractDataFromFile()
	 */
	protected function getAll_rawData_extractDataFromFile(\SimpleXMLElement $xml)
	{

		$return = [];
		foreach($xml->sender as $sender) {
			if ((String)$sender->email) {
				$return[(String)$sender['type']] = [
					'email'=>(String)$sender->email,
					'name'=>(String)$sender->name
				];
			}
		}

		return $return;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Config\BaseAbstract::save_check()
	 */
	protected function save_check()
	{
		foreach ($this->itemsList as $type => $typeDet) {
			if (!in_array($type, $this->senderTypes)) {
				$this->addErrorMessage(sprintf('The email type `%s` is not valid.', $type));
			}

			if (!$typeDet['email'] && $typeDet['name']) {
				$this->addErrorMessage(sprintf('Cannot set name without email for `%s` type.', $type));
			}

			// the invoice and cashing email fields aren't mandatory
			if (in_array($type, ['invoice', 'cashing'])) {
				if ($typeDet['email'] && !\Engine\Validator::set($typeDet['email'])->isEmail()) {
					$this->addErrorMessage(sprintf('Email for type `%s` is not valid.', $type));
				}
			}
			else {
				if (!$typeDet['email'] || !\Engine\Validator::set($typeDet['email'])->isEmail()) {
					$this->addErrorMessage(sprintf('Email for type `%s` is not set or valid.', $type));
				}
			}
		}
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Config\XmlBasicAbstract::save_write_do_getXml()
	 */
	protected function save_write_do_getXml()
	{

		// start composing the XML object
		$xml=simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><autoEmailSender />');

		foreach($this->senderTypes as $type) {
			if ($this->itemsList[$type]['email']) {
				$sender=$xml->addChild('sender');
				$sender['type']=$type;
				$sender->email=$this->itemsList[$type]['email'];
				if ($this->itemsList[$type]['name']) {
					$sender->name=$this->itemsList[$type]['name'];
				}
			}
		}

		// return the simplexml object
		return $xml;

	}

	/**
	 * return sender types
	 */
	public function getSenderTypes()
	{
		return $this->senderTypes;
	}

}