<?php
namespace SabaiApps\Framework\Model\EntityCollection;

/**
 * ParentEntitiesCountEntityCollectionDecorator class for decorating entity collections with parent entity counts.
 * Adds functionality to calculate and assign the count of parent entities for each entity in the collection.
 */
class ParentEntitiesCountEntityCollectionDecorator extends AbstractEntityCollectionDecorator {

	protected $_entityName, $_parentEntitiesCount;

	/**
	 * Constructor.
	 *
	 * @param string                   $entityName Name of the parent entity.
	 * @param AbstractEntityCollection $collection Entity collection to decorate.
	 */
	public function __construct( $entityName, AbstractEntityCollection $collection ) {
		parent::__construct( $collection );
		$this->_entityName = $entityName;
	}

	/**
	 * Rewinds the collection and calculates parent entity counts.
	 */
	#[\ReturnTypeWillChange]
	public function rewind() {
		$this->_collection->rewind();
		if ( ! isset( $this->_parentEntitiesCount ) ) {
			$this->_parentEntitiesCount = array();
			if ( $this->_collection->count() > 0 ) {
				$this->_parentEntitiesCount = $this->_model->getRepository( $this->_entityName )->countParentsByIds( $this->_collection->getAllIds() );
				$this->_collection->rewind();
			}
		}
	}

	/**
	 * Gets the current entity and assigns its parent entity count.
	 *
	 * @return mixed Current entity with parent entity count.
	 */
	#[\ReturnTypeWillChange]
	public function current() {
		$current = $this->_collection->current();
		$id      = $current->id;
		$current->setParentsCount( isset( $this->_parentEntitiesCount[ $id ] ) ? $this->_parentEntitiesCount[ $id ] : 0 );

		return $current;
	}
}
