<?php

namespace App\Config;

class SupplierInvoice_Services 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_SUPPLIERINVOICES_SERVICES;


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

		// get the full list of services
		$allServList=Services_Basic::getInstance()->getListLinear();

		// gets the list of disabled services
		$disabledServ=[];
		foreach($xml->service  as $serv) {
			$servCode=(String)$serv['code'];
			$disabled=(Int)$serv['disabled'];
			if ($disabled) $disabledServ[$servCode]=true;
		}

		// gets the list of services active/inactive to be returned
		$return=[];
		foreach($allServList as $servCode=>$nothing) {
			if ($disabledServ[$servCode]) $return[$servCode]=false;
			else $return[$servCode]=true;
		}

		return $return;
	}

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

		// gets the list of services active/inactive to be returned
		$return=[];
		foreach(Services_Basic::getInstance()->getListLinear() as $servCode=>$nothing) {
			$return[$servCode]=true;
		}
		return $return;
	}

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

		// check each service code
		foreach($this->itemsList as $code=>$nothing) {
			if (!Services_Basic::getInstance()->checkService($code)) $this->addErrorMessage(sprintf('The service code `%s` is not valid.', $code));
		}
	}


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

		// get the full list of services
		$allServList=Services_Basic::getInstance()->getListLinear();

		// LOOP THROUGH EACH SERVICE CODE AVAILABLE IN THE APP ------------------------------------
		foreach($allServList as $serviceCode=>$nothing) {
			// if the field is false (not enabled) - save it into the XML
			if (!$this->itemsList[$serviceCode]) {
				$servObj=$xml->addChild('service');
				$servObj['code']=$serviceCode;
				$servObj['disabled']=true;
			}

		}

		// return the simplexml object
		return $xml;
	}

}
