<?php
namespace SabaiApps\Framework\DB;

/**
 * RowsetIterator class for iterating over rowsets.
 * Implements Iterator and Countable interfaces for flexible rowset traversal.
 */
class RowsetIterator implements \Iterator, \Countable {

	protected $_rs, $_key, $_count;

	/**
	 * Constructor.
	 *
	 * @param AbstractRowset $rs Rowset object.
	 */
	public function __construct( AbstractRowset $rs ) {
		$this->_rs  = $rs;
		$this->_key = 0;
	}

	/**
	 * Rewinds the iterator to the first element.
	 */
	#[\ReturnTypeWillChange]
	public function rewind() {
		$this->_key = 0;
	}

	/**
	 * Checks if the current element is valid.
	 *
	 * @return bool True if valid, false otherwise.
	 */
	#[\ReturnTypeWillChange]
	public function valid() {
		return $this->_rs->seek( $this->_key );
	}

	/**
	 * Moves to the next element.
	 */
	#[\ReturnTypeWillChange]
	public function next() {
		++$this->_key;
	}

	/**
	 * Gets the current element.
	 *
	 * @return mixed Current row data.
	 */
	#[\ReturnTypeWillChange]
	public function current() {
		return $this->_rs->fetchAssoc();
	}

	/**
	 * Gets the key of the current element.
	 *
	 * @return int Current key.
	 */
	#[\ReturnTypeWillChange]
	public function key() {
		return $this->_key;
	}

	/**
	 * Counts the number of elements in the rowset.
	 *
	 * @return int Number of rows.
	 */
	#[\ReturnTypeWillChange]
	public function count() {
		if ( ! isset( $this->_count ) ) {
			$this->_count = $this->_rs->rowCount();
		}
		return $this->_count;
	}

	/**
	 * Fetches the current row as a numeric array.
	 *
	 * @return array|false Row data or false on failure.
	 */
	public function row() {
		return $this->_rs->fetchRow();
	}
}
