<?php
namespace App\Config;

class AgencyDocumentsEmail 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_AGENCYDOCUMENTSEMAIL;

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

		foreach ($xml->pivots as $pivots) {
			foreach ($pivots as $pivotCode => $values) {
				$results[(String)$pivotCode]['subject'] = 	(String)$values->subject;
				$results[(String)$pivotCode]['body'] = 		(String)$values->body;
			}
		}

		return $results;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Config\BaseAbstract::save_check()
	 */
	protected function save_check()
	{
		if ($this->itemsList['pivots']) {
			$allowedPivotsList = ['order', 'service', 'invoice', 'cashing', 'payment', 'balance', 'cashBookDoc', 'importedService', 'importedDocument'];
			foreach ($this->itemsList['pivots'] as $pivot => $values) {
				// validate pivot
				if (!in_array($pivot, $allowedPivotsList)) {
					throw new \Exception(sprintf("The pivot %s is not valid.", $pivot));
				}

				// validate values
				if (!$values) {
					throw new \Exception("The document emails details for each pivot mutst be set.");
				}
			}
		}
	}

	/**
	 * (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"?><documentsEmail/>');

		if ($this->itemsList['pivots']) {
			$pivotsChild = $xml->addChild('pivots');
			foreach ($this->itemsList['pivots'] as $pivot => $values) {
				$pivotChild = $pivotsChild->addChild($pivot);
				foreach ($values as $k => $v) {
					$pivotChild->addChild($k, $v);
				}
			}
		}

		return $xml;
	}

	public function getSubject($pivot)
	{
		$list = $this->getAll();
		return $list[$pivot]['subject'];
	}

	public function getBody($pivot)
	{
		$list = $this->getAll();
		return $list[$pivot]['body'];
	}
}