<?php

namespace KupShop\I18nBundle\Util;

use KupShop\I18nBundle\Translations\TranslationCustomDataInterface;

trait TranslationCustomDataTrait
{
    protected $customDataColumns = [];

    public function getColumns(): array
    {
        $columns = $this->columns;

        if ($this instanceof TranslationCustomDataInterface) {
            $columns['data'] = [];
        }

        return $columns;
    }

    public function getCustomDataColumns(): array
    {
        return $this->customDataColumns;
    }

    public function handleSaveCustomData($customData, $actualData, &$values): bool
    {
        $data = array_filter(array_merge(json_decode($actualData, true) ?: [], $customData));
        $values['data'] = !empty($data) ? json_encode($data) : null;
        unset($values['custom_data']);

        return true;
    }

    public function setCustomDataColumns($columns)
    {
        if (!is_array($columns)) {
            $columns = [];
        }

        $customDataColumns = array_merge($this->customDataColumns, $columns);

        foreach ($customDataColumns as $column => &$config) {
            $config['custom_data'] = true;
            $config['field'] = 'data';
        }

        $this->customDataColumns = $customDataColumns;
    }
}
