<?php

$grid = array_map('str_split', explode("\n", file_get_contents('./input.txt')));

$steps = 0;

while (!are_synchronized($grid)) {
    foreach ($grid as $k => $row) {
        foreach ($row as $j => $cell) {
            $grid[$k][$j]++;
        }
    }

    while(has_more_than_nine($grid)) {
        foreach ($grid as $k => $row) {
            foreach ($row as $j => $cell) {
                if ($grid[$k][$j] > 9) {
                    foreach (range(-1, 1) as $r) {
                        foreach (range(-1, 1) as $c) {
                            if ($r === 0 && $c === 0) {
                                $grid[$k+$r][$j+$c] = 0;
                            }
                            if (
                                array_key_exists($k+$r, $grid) &&
                                array_key_exists($j+$c, $grid[$k+$r]) &&
                                $grid[$k+$r][$j+$c] !== 0
                            ) {
                                $grid[$k+$r][$j+$c]++;
                            }
                        }
                    }
                }
            }
        }
    }

    $steps++;

    echo sprintf('After step %u%s%s%s%s', $steps, "\n", implode("\n", array_map('implode', $grid)), "\n", "\n");
}

echo $steps;

function has_more_than_nine($grid)
{
    foreach ($grid as $row) {
        foreach ($row as $cell) {
            if ($cell > 9) {
                return true;
            }
        }
    }

    return false;
}

function are_synchronized($grid)
{
    foreach ($grid as $row) {
        foreach ($row as $cell) {
            if ($cell !== 0) {
                return false;
            }
        }
    }

    return true;
}