<?php

/**
 * PHP-IR statement for PHP if / elseif / else control flow.
 */
final class PhpIrIf
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private object $cond;
    private array $stmts;
    private array $elseifs;
    private array $elseStmts;

    /**
     * Create a conditional statement.
     *
     * @param int $startLine Original PHP start line.
     * @param int $endLine Original PHP end line.
     * @param array $comments PHP-IR comments attached to the statement.
     * @param object $cond PHP-IR expression whose PHP truthiness decides the branch.
     * @param array $stmts PHP-IR statements for the `if` branch.
     * @param array $elseifs List of ['cond' => object, 'stmts' => array] entries.
     * @param array $elseStmts PHP-IR statements for the optional `else` branch.
     */
    public function __construct(int $startLine, int $endLine, array $comments, object $cond, array $stmts, array $elseifs = [], array $elseStmts = [])
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->cond = $cond;
        $this->stmts = $stmts;
        $this->elseifs = $elseifs;
        $this->elseStmts = $elseStmts;
    }

    /** Convert to a plain array for debugging/export. */
    public function toArray(): array
    {
        return [
            'kind' => 'If',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (PhpIrComment $comment): array => $comment->toArray(), $this->comments),
            'cond' => method_exists($this->cond, 'toArray') ? $this->cond->toArray() : ['kind' => get_debug_type($this->cond)],
            'stmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->stmts),
            'elseifs' => array_map(static function (array $elseif): array {
                $cond = $elseif['cond'] ?? null;
                $stmts = is_array($elseif['stmts'] ?? null) ? $elseif['stmts'] : [];
                return [
                    'cond' => is_object($cond) && method_exists($cond, 'toArray') ? $cond->toArray() : ['kind' => get_debug_type($cond)],
                    'stmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $stmts),
                ];
            }, $this->elseifs),
            'elseStmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->elseStmts),
        ];
    }
}
