<?php
namespace App\Form\Input;

class Select_DocumentType extends \Engine\Form\Input\Select
{

	/**
	 * The pivot filtering - it can be 'invoice', 'order', 'service' etc
	 * @var String
	 */
	protected $pivot = null;

	/**
	 * Filter by some document category
	 * @var String
	 */
	protected $docCategory = null;

	/**
	 * For service pivot, this sets the filter of doc types based on service code (if not set, all service types are included).
	 * @var String
	 */
	protected $serviceCode = null;

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Select::__construct()
	 */
	public function __construct($label=null, $name=null, $value=null, $possibleValues=null)
	{
		parent::__construct($label, $name, $value);

		$this->showDefaultOption(true);
	}

	/**
	 * Sets the pivot filter.
	 * @param String $pivot
	 */
	public function setPivot($pivot)
	{
		$this->pivot = $pivot;
	}

	/**
	 * Sets document category
	 * @param String $docCategory
	 */
	public function setDocCategory($docCategory)
	{
		$this->docCategory = $docCategory;
	}

	/**
	 * Sets the service code.
	 * @param String $serviceCode
	 */
	public function setServiceCode($serviceCode)
	{
		if ($this->pivot!='service') {
			throw new \Exception('You cannot set the service code unless the pivot is set as `service`.');
		}
		$this->serviceCode = $serviceCode;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Select::determinePossibleValues()
	 */
	protected function determinePossibleValues()
	{

		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		$docCfgObj = \App\Config\IssueDocuments::getInstance();;

		// indicate which doc types should be included when filtering by service code
		$filterByServiceCode = [];
		if ($this->serviceCode) {
			$filterByServiceCode = $docCfgObj->getServiceDocsList($this->serviceCode);
		}

		// collect doc types, grouped by pivot and filtered by all available criteria
		$assocDocTypes = [];
		foreach($docCfgObj->getAll() as $docType=>$docDetails) {

			// skip inactive docs
			if (!$docDetails['active']) {
				continue;
			}
			// skip docs filtered by pivot
			if ($this->pivot and $docDetails['pivot']!=$this->pivot) {
				continue;
			}
			// skip docs filtered by docCategory
			if ($this->docCategory and $docDetails['docCategory']!=$this->docCategory) {
				continue;
			}
			// skip docs filtered by service code
			if ($filterByServiceCode and !$filterByServiceCode[$docType]) {
				continue;
			}

			if ($this->pivot) { // if filtered by pivot
				$assocDocTypes [$docType] = $docDetails['name'];
			} else { // not filtered by pivot (many pivots may be available
				$assocDocTypes [$_LANG['documentPivotName'][$docDetails['pivot']]] [$docType] = $docDetails['name'];
			}
		}

		return $assocDocTypes;
	}

}