<?php
namespace SabaiApps\Directories\Component;

use SabaiApps\Framework\Model\EntityCollection\AbstractEntityCollection;
use SabaiApps\Framework\Model\EntityCollection\AbstractEntityCollectionDecorator;

/**
 * ModelEntityWithUser decorates an entity collection to attach user identity objects.
 * Automatically loads and assigns user identity objects to each entity in the collection.
 */
abstract class ModelEntityWithUser extends AbstractEntityCollectionDecorator {

	protected $_userIdentities, $_userKeyVar, $_userEntityObjectVarName;

	/**
	 * Constructor.
	 *
	 * @param AbstractEntityCollection $collection
	 * @param string                   $userKeyVar The property name for user ID.
	 * @param string                   $userEntityObjectVarName The property name to assign the user identity object.
	 */
	public function __construct( AbstractEntityCollection $collection, $userKeyVar = 'user_id', $userEntityObjectVarName = 'User' ) {
		parent::__construct( $collection );
		$this->_userKeyVar              = $userKeyVar;
		$this->_userEntityObjectVarName = $userEntityObjectVarName;
	}

	/**
	 * Rewinds the collection and loads user identities for all entities.
	 */
	#[\ReturnTypeWillChange]
	public function rewind() {
		$this->_collection->rewind();
		if ( ! isset( $this->_userIdentities ) ) {
			$this->_userIdentities = array();
			if ( $this->_collection->count() > 0 ) {
				$user_ids = array();
				while ( $this->_collection->valid() ) {
					$user_ids[] = $this->_collection->current()->{$this->_userKeyVar};
					$this->_collection->next();
				}
				$this->_userIdentities = $this->_model->UserIdentity( array_unique( $user_ids ) );
				$this->_collection->rewind();
			}
		}
	}

	/**
	 * Returns the current entity with the user identity object assigned.
	 *
	 * @return object
	 */
	#[\ReturnTypeWillChange]
	public function current() {
		$current = $this->_collection->current();
		$current->assignObject( $this->_userEntityObjectVarName, $this->_userIdentities[ $current->{$this->_userKeyVar} ] );

		return $current;
	}
}
