<?php

/**
 * PHP-IR statement for PHP for-loop control flow.
 */
final class PhpIrFor
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private array $initStmts;
    private array $condExprs;
    private array $loopStmts;
    private array $stmts;

    /**
     * Create a for-loop statement.
     *
     * @param int $startLine Original PHP start line.
     * @param int $endLine Original PHP end line.
     * @param array $comments PHP-IR comments attached to the loop.
     * @param array $initStmts PHP-IR statements executed once before the loop.
     * @param array $condExprs PHP-IR condition expressions; all must be truthy.
     * @param array $loopStmts PHP-IR statements executed after each iteration.
     * @param array $stmts PHP-IR body statements.
     */
    public function __construct(int $startLine, int $endLine, array $comments, array $initStmts, array $condExprs, array $loopStmts, array $stmts)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->initStmts = $initStmts;
        $this->condExprs = $condExprs;
        $this->loopStmts = $loopStmts;
        $this->stmts = $stmts;
    }

    /** Convert to a plain array for debugging/export. */
    public function toArray(): array
    {
        return [
            'kind' => 'For',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (PhpIrComment $comment): array => $comment->toArray(), $this->comments),
            'initStmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->initStmts),
            'condExprs' => array_map(static fn (object $expr): array => method_exists($expr, 'toArray') ? $expr->toArray() : ['kind' => get_debug_type($expr)], $this->condExprs),
            'loopStmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->loopStmts),
            'stmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->stmts),
        ];
    }
}
