<?php

namespace Wizzard\MagicForger\Replacer;

trait TableReplacer
{
    protected $columns;

    protected function get_columns()
    {
        if (is_null($this->columns)) {
            $this->columns = $this->getCurrentTable()->getColumns();
        }

        return $this->columns;
    }

    protected function get_attributes()
    {
    }

    protected function getValuesForCreation()
    {
        $insert = '';
        foreach ($this->get_columns() as $column) {
            $insert .= '$item->'.$column->getName().' = $validated["'.$column->getName().'"] ?? NULL;'."\n";
        }

        return $insert;
    }

    public function apply_inserts(string $target): string
    {
        $inserts = $this->get_all_keywords($target);
        $available_replacements = $this->get_available_inserts();

        $target = str_replace(
            array_keys($available_replacements),
            $available_replacements,
            $target
        );

        return $target;
    }

    public function get_available_inserts()
    {
        $table_name = $this->getTableInput();
        $replacements = [
                        '// {{ valuesForCreation }}' => self::getValuesForCreation(),
        ];

        foreach ($replacements as $key => &$replacement) {
            $replacement = $replacement."\n".$key;
        }

        return $replacements;
    }
}
