<?php

namespace App\Config;

/**
 * The class is used for managing due dates from the invoices
 * @author Bogdan
 */
class InvoiceDueDates 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_INVOICES_DUE_DATES;

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

		// get a list from xml file with due dates depending on client's categories
		$clientCategoriesList=[];
		foreach ($xml as $clientCategories) {
			$clientCategoriesList[(string)$clientCategories->getName()] = (int)$clientCategories;
		}
		return $clientCategoriesList;
	}

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

		// get a list with three keys: corporate,subagent and customer
		$return= [
			'corporate' => 0,
			'subagent' => 0,
			'customer' => 0
		];
		return $return;
	}


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

		// get a list of allowed client's categories
		$allowedClientCategoriesList= ['corporate', 'subagent', 'customer'];

		// scan each categories
		foreach ($this->itemsList as $category => $daysNumber) {

			// check client's category
			if ( !in_array($category, $allowedClientCategoriesList) ) {
				$this->addErrorMessage('An invalid category was requested: '.$category);
			}
			if ($daysNumber) {
				// number of days to due date
				if ( !is_numeric($daysNumber) or $daysNumber<0 or $daysNumber>366 ) {
					$this->addErrorMessage('Number of days until due dates for `'.$category.' category` must be a numeric value between 0 and 366 ');
				}
			}
		}
	}

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

		// scan each item
		foreach ( $this->itemsList as $clientCategory => $days ) {
			if($days=='') {
				$days=0;
			}
			// add the client category tag
			$xml->addChild($clientCategory, $days);
		}

		// return the simplexml object
		return $xml;
	}

}


