<?php

/**
 * Created by PhpStorm.
 * User: Igor Ratsun
 * Date: 6/12/23
 * Time: 6:57 PM
 */
class Rtgc_collection extends Abstract_rtgc_callback
{
    protected $options = [
        'collection' => [],
    ];

    public function __construct($opt = [])
    {
        $this->set_options($opt);
    }

    public function set_options($opt = [])
    {
        if (is_array($opt)) {
            $this->options = array_merge($this->options, $opt);
        }

        if (empty($this->options['crud'])) {
            show_error('Please, set CRUD library');
        }

        if (empty($this->options['field'])) {
            show_error('Please, set `field` key');
        }

        $field = $this->options['field'];

        $this->options['crud']->callback_before_edit(function ($post_data, $pkey) use ($field) {
            $post_data[$field] = json_encode($post_data[$field]);
            return $post_data;
        });

        return $this;
    }

    public function column($value = '')
    {
        $values = !empty($value) ? json_decode(htmlspecialchars_decode($value), true) : [];

        return count($values);
    }

    public function field($name = '', $value = null)
    {
        $content = [];

        if (is_array($value)) {
            $values = $value;
        } else {
            $values = !empty($value) ? json_decode(htmlspecialchars_decode($value), true) : [];
        }

        foreach ($this->options['collection'] as $item) {
            $content[] = [
                'name'    => $item['label'],
                'value'   => $item['callback']->field($name . '[' . $item['name'] . ']', $values[$item['name']] ?? ''),
                'tooltip' => '',
            ];
        }

        return get_instance()->parser->parse($this->options['crud']->get_option('template')['fields_item'], ['field' => $content], true);
    }

    public function add_item($name, \Rtgc_callback $callback, $label = ''): self
    {
        $this->options['collection'][] = [
            'name'     => $name,
            'callback' => $callback,
            'label'    => $label,
        ];

        return $this;
    }
}