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

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

	protected $_entityName, $_childEntitiesCount;

	/**
	 * Constructor.
	 *
	 * @param string                   $entityName Name of the child 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 child entity counts.
	 */
	#[\ReturnTypeWillChange]
	public function rewind() {
		$this->_collection->rewind();
		if ( ! isset( $this->_childEntitiesCount ) ) {
			$this->_childEntitiesCount = array();
			if ( $this->_collection->count() > 0 ) {
				$parent_ids                = $this->_collection->getAllIds();
				$this->_childEntitiesCount = $this->_model->getRepository( $this->_entityName )->countByParent( $parent_ids );
				$this->_collection->rewind();
			}
		}
	}

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

		return $current;
	}
}
