<?php
namespace SabaiApps\Framework\Model;

use SabaiApps\Framework\DB\AbstractRowset;

/**
 * AbstractTreeGateway class for managing database operations for hierarchical entities.
 * Provides methods for selecting and counting parent, child, and descendant entities.
 */
abstract class AbstractTreeGateway extends AbstractGateway {

	/**
	 * Selects all descendant entities of a given parent entity.
	 *
	 * @param string $id Parent entity ID.
	 * @param array  $fields Fields to select.
	 * @return AbstractRowset Rowset of descendant entities.
	 */
	public function selectDescendants( $id, array $fields = array() ) {
		return $this->selectBySQL( $this->_getSelectDescendantsQuery( $id, $fields ) );
	}

	/**
	 * Counts all descendant entities of a given parent entity.
	 *
	 * @param string $id Parent entity ID.
	 * @return int Number of descendant entities.
	 */
	public function countDescendants( $id ) {
		return $this->_db->query( $this->_getCountDescendantsQuery( $id ) )->fetchSingle();
	}

	/**
	 * Counts descendant entities for multiple parent entity IDs.
	 *
	 * @param array $ids Array of parent entity IDs.
	 * @return AbstractRowset Rowset of counts for each parent entity ID.
	 */
	public function countDescendantsByIds( $ids ) {
		return $this->_db->query( $this->_getCountDescendantsByIdsQuery( $ids ) );
	}

	/**
	 * Selects all parent entities of a given entity.
	 *
	 * @param string $id Entity ID.
	 * @param array  $fields Fields to select.
	 * @return AbstractRowset Rowset of parent entities.
	 */
	public function selectParents( $id, array $fields = array() ) {
		return $this->selectBySQL( $this->_getSelectParentsQuery( $id, $fields ) );
	}

	/**
	 * Counts all parent entities of a given entity.
	 *
	 * @param string $id Entity ID.
	 * @return int Number of parent entities.
	 */
	public function countParents( $id ) {
		return $this->_db->query( $this->_getCountParentsQuery( $id ) )->fetchSingle();
	}

	/**
	 * Counts parent entities for multiple entity IDs.
	 *
	 * @param array $ids Array of entity IDs.
	 * @return AbstractRowset Rowset of counts for each entity ID.
	 */
	public function countParentsByIds( $ids ) {
		return $this->_db->query( $this->_getCountParentsByIdsQuery( $ids ) );
	}
}
