<?php

namespace App\Entity\Utils;

class PivotDocumentsList
{

	/**
	 * The documents pivot (reservation, service, invoice, cashing).
	 * @var String
	 */
	private $pivot;

	/**
	 * The pivot id.
	 * @var Int
	 */
	private $idPivot;

	/**
	 * Sets the pivot details.
	 * @param String $pivot
	 * @param Int $idPivot
	 * @throws \Exception - if pivot type is not valid
	 */
	public function __construct($pivot, $idPivot)
	{

		// check the input
		if ($pivot!='order' and $pivot!='service' and $pivot!='invoice' and $pivot!='cashing' and $pivot!='payment' and $pivot != 'cashBookDoc' and $pivot != 'importedService' and $pivot != 'importedDocument' and $pivot != 'balance') {
			throw new \Exception('The document pivot is not valid - '.$pivot);
		}

		// set the main fields
		$this->pivot=$pivot;
		$this->idPivot=$idPivot;

	}

	/**
	 * Returns the list of documents attached to the current pivot.
	 * @return Array
	 */
	public function getDocumentsList($selectForUpdate)
	{

		// return an empty array for an invalid pivot id
		if (!is_numeric($this->idPivot) or $this->idPivot<=0) {
			return [];
		}
		// get documents list from db
		$dlObj=new \App\EntityList\Documents();
		$dlObj->setFilter('doc.pivot', '=', $this->pivot);
		$dlObj->setFilter('doc.idPivot', '=', $this->idPivot);

		if ($this->pivot == 'cashBookDoc') {
			$cashBookDate = \Entity\CashBookDocument::select($this->idPivot)->date;
			$tableMonth = \Engine\DateTime::createFromIsoDate($cashBookDate)->format('Ym');
			$startIndex = \App\Utils\Db\TablesUtils::getInstance()->getStartIndexFromYm($tableMonth);
			$endIndex = \App\Utils\Db\TablesUtils::getInstance()->getEndIndexFromYm($tableMonth);
			$dlObj->setFilter('doc.id', 'BETWEEN', [$startIndex, $endIndex]);
		}

		if ($this->pivot == 'importedService') {
			$tableMonth = \Engine\DateTime::createFromIsoDatetime(\Entity\ImportedService::select($this->idPivot)->addTime)->format('Ym');
			$startIndex = \App\Utils\Db\TablesUtils::getInstance()->getStartIndexFromYm($tableMonth);
			$endIndex = \App\Utils\Db\TablesUtils::getInstance()->getEndIndexFromYm($tableMonth);
			$dlObj->setFilter('doc.id', 'BETWEEN', [$startIndex, $endIndex]);
		}
		if ($this->pivot == 'importedDocument') {
			$tableMonth = \Engine\DateTime::createFromIsoDatetime(\Entity\ImportedDocument::select($this->idPivot)->addTime)->format('Ym');
			$startIndex = \App\Utils\Db\TablesUtils::getInstance()->getStartIndexFromYm($tableMonth);
			$endIndex = \App\Utils\Db\TablesUtils::getInstance()->getEndIndexFromYm($tableMonth);
			$dlObj->setFilter('doc.id', 'BETWEEN', [$startIndex, $endIndex]);
		}

		$dlObj->applyUserRestriction(false);
		$dlObj->setColumns(['doc.docType', 'doc.idTemplate', 'doc.format', 'doc.docNumber', 'doc.docDate', 'doc.docFile', 'doc.preview', 'doc.generation', 'doc.comments', 'doc.fieldsDetails', 'doc.history', 'doc.extraInfo']);
		$dlObj->setForUpdate($selectForUpdate);
		$dlObj->setOrderBy('doc.id', 'ASC');

		$docsList=$dlObj->getExecution();

		// create an associative array and unserialize the fields
		$finalList=[];
		$genCount=[];

		foreach($docsList as $doc) {
			$idDoc=$doc['id'];
			$finalList[$idDoc]=$doc;
			if ($doc['fieldsDetails']) {
				$finalList[$idDoc]['fieldsDetails']=unserialize($doc['fieldsDetails']);
			} else {
				$finalList[$idDoc]['fieldsDetails']=[];
			}
			if ($doc['extraInfo']) {
				$ei=unserialize($doc['extraInfo']);
			} else {
				$ei=[];
			}
			$finalList[$idDoc]['extraInfo']=$ei;
			unset($finalList[$idDoc]['id']);
			$finalList[$idDoc]['history']=unserialize($doc['history']);
			// extract servicesList/voided/series from extraInfo
			if ($ei['servicesList']) {
				$finalList[$idDoc]['servicesList']=$ei['servicesList'];
			}
			$finalList[$idDoc]['voided']=(Boolean)$ei['voided'];
			if ($ei['idDocumentSeries']) {
				$finalList[$idDoc]['idDocumentSeries']=$ei['idDocumentSeries'];
			}
			// store the generation count
			if (!$doc['preview'] and $doc['generation']=='auto') {
				$genCount[$doc['docType']]++;
			}
			$finalList[$idDoc]['genCount']=$genCount[$doc['docType']];
			// store the 'printed' flag
			$finalList[$idDoc]['printed']=false;
			if ($finalList[$idDoc]['history']) {
				foreach($finalList[$idDoc]['history'] as $item) {
					if ($item['op']=='p') {
						$finalList[$idDoc]['printed']=true;
						break;
					}
				}
			}

			// store the add user/time
			$finalList[$idDoc]['idAddUser']=$finalList[$idDoc]['history'][0]['us'];
			$finalList[$idDoc]['addTime']=$finalList[$idDoc]['history'][0]['t'];

		}

		// return the documents list
		return $finalList;

	}

}