<?php

namespace App\Config;

/**
 * The class is used for managing service offer confirmations: offerConfirmationMode, showExtSysResId, showExtSysResDate
 */
class Services_OfferConfirmations extends XmlBasicAbstract {

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


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

		// get the list of offer details grouped by services
		$result=[];

		// scan the services list from XML file
		foreach($xml->service as $serviceOfferDetails) {

			$serviceOfferConfirmationsList = [];

			// set the confirmation mode (allwaysConfirmed, defaultConfirmed or defaultNotConfirmed )
			$serviceOfferConfirmationsList['offerConfirmationMode'] = (string)$serviceOfferDetails->offerConfirmationMode;

			// put service offer details in array which will be returned
			$result[(string)$serviceOfferDetails['code']]=$serviceOfferConfirmationsList;
		}

		return $result;
	}


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

		// scan each service from the session
		foreach (Services_Basic::getAdmin()->getListLinear() as $serviceCode => $serviceDetails) {

			// check the quantity type
			if ( !in_array($this->itemsList[$serviceCode]['offerConfirmationMode'], ['alwaysConfirmed', 'defaultConfirmed', 'defaultNotConfirmed'])) {
				$this->addErrorMessage('When setting the service offer details, the offer `confirmation mode` is not valid for service `'.$serviceDetails['name'].'`.');
			}

		}
	}

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

		// scan each service from the session
		foreach (Services_Basic::getAdmin()->getListLinear() as $serviceCode => $serviceDetails) {

			// add the service tag
			$serviceObj=$xml->addChild('service');
			$serviceObj['code']=$serviceCode;

			// add the confirmation mode of service offer (allwaysConfirmed, defaultConfirmed or defaultNotConfirmed )
			$serviceObj->offerConfirmationMode = $this->itemsList[$serviceCode]['offerConfirmationMode'];
		}

		// return the simplexml object
		return $xml;
	}

}
