<?php
namespace App\Mvc\View\Utils\RowOptions\Option\Popup;

/**
 * Helper class to define option for generate documents on the following pivot:
 * 				invoice, cashing, payment, order, service, cashBookDoc, importedService
 * @author Oana Stan
 */
class ManageDocuments extends \App\Mvc\View\Utils\RowOptions\Option\Option
{
	/**
	 * Stores the type of pivot
	 * @var String
	 */
	protected $pivot = NULL;

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\View\Utils\RowOptions\Option\Option::init()
	 */
	protected function init()
	{
		$this->setIcon('documents');
	}

	/**
	 * Checks and sets the pivot for doc gen option.
	 * @param string  $pivot
	 */
	public function setPivot(string $pivot)
	{

		// validate pivot
		if (!in_array($pivot, ['invoice', 'cashing', 'payment', 'order', 'service', 'cashBookDoc', 'importedService', 'importedDocument', 'balance'])) {
			throw new \Exception(sprintf('Invalid pivot type set using method `%s`', __METHOD__));
		}
		$this->pivot = $pivot;

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

		$this->customJsCallback = "loadPivotGenerateDoc(this, '{$_LANG['generateDocument']['divTitle']}', '{$pivot}', MVC.listing.installedHandlers.listing.getItemId(this))";

	}

	/**
	 * Create an option item
	 * @return self
	 */
	public static function createWithPivot($id, string $pivot)
	{
		$obj = new self($id);
		$obj->setPivot($pivot);
		return $obj;
	}


	/**
	 * Determine icon for this option
	 * @param String $idPivot
	 * @return \App\Mvc\View\Utils\RowOptions\Option\Popup\ManageDocuments
	 */
	public function determineIconGeneratedDocuments($idPivot)
	{
		// get pivot details
		switch ($this->pivot) {
			case 'order': {
				$pivotObj = \Entity\Order::select($idPivot);
				break;
			}
			case 'service': {
				$pivotObj = \Entity\Service::select($idPivot);
				break;
			}
			case 'invoice': {
				$pivotObj = \Entity\Invoice::select($idPivot);
				break;
			}
			case 'cashing': {
				$pivotObj = \Entity\InvoiceCashing::select($idPivot);
				break;
			}
			case 'payment': {
				$pivotObj = \Entity\SupplierInvoicePayment::select($idPivot);
				break;
			}
			case 'cashBookDoc': {
				$pivotObj = \Entity\CashBookDocument::select($idPivot);
				break;
			}
			case 'importedService': {
				$pivotObj = \Entity\ImportedService::select($idPivot);
				break;
			}
			case 'importedDocument': {
				$pivotObj = \Entity\ImportedDocument::select($idPivot);
				break;
			}
			case 'balance': {
				$pivotObj = \Entity\Balance::select($idPivot);
				break;
			}
			default: {
				throw new \Exception('Invalid pivot  type in `'.__METHOD__.'` method call.');
			}
		}

		$documentsList = $pivotObj->documentsList;

		if ($documentsList) {
			foreach ($documentsList as $documentDetails) {
				if (!$documentDetails['preview']) {
					$this->setIcon('issuedDoc');
					break;
				}
			}

		}

		return $this;
	}

	public function reset()
	{
		$this->setIcon('documents');
		return parent::reset();
	}

}