<?php

declare(strict_types=1);

namespace PpPhp\Core;

/**
 * Lightweight wrapper around a PDOStatement, mimicking PHPRunner's QueryResult object.
 *
 * Usage:
 *   $result = DB::Query("SELECT * FROM users WHERE id=?", [$id]);
 *   while ($row = $result->fetchAssoc()) { … }
 *   $name = $result->value('name');
 */
class QueryResult
{
    public function __construct(private \PDOStatement $stmt) {}

    /** Fetch next row as an associative array (or null when exhausted). */
    public function fetchAssoc(): ?array
    {
        $row = $this->stmt->fetch(\PDO::FETCH_ASSOC);
        return ($row !== false) ? $row : null;
    }

    /** Fetch next row as a numeric array (or null when exhausted). */
    public function fetchNumeric(): ?array
    {
        $row = $this->stmt->fetch(\PDO::FETCH_NUM);
        return ($row !== false) ? $row : null;
    }

    /** Return the value of a specific field from the first row. */
    public function value(string $field = ''): mixed
    {
        $row = $this->stmt->fetch(\PDO::FETCH_ASSOC);
        if ($row === false) {
            return null;
        }
        if ($field !== '') {
            return $row[$field] ?? null;
        }
        // Return the first column if no field name given
        return reset($row);
    }

    /**
     * Return all remaining rows.
     *
     * @param int $fetchStyle  PDO fetch style (default FETCH_ASSOC).
     * @return array
     */
    public function fetchAll(int $fetchStyle = \PDO::FETCH_ASSOC): array
    {
        return $this->stmt->fetchAll($fetchStyle);
    }

    /** Return the number of rows affected by the last statement. */
    public function rowCount(): int
    {
        return $this->stmt->rowCount();
    }

    /** Return the raw PDOStatement for advanced use. */
    public function stmt(): \PDOStatement
    {
        return $this->stmt;
    }
}
