<?php

class Inline_collection
{
    private $ci;

    public function __construct()
    {
        $this->ci = get_instance();
        $this->ci->load->model('inlineeditor/inlineeditor_text_tmodel');
        $this->ci->load->library('inlineeditor/inline_base');
    }

    public function parse($collection_name, $template, $values = [], $i_id = null)
    {
        $template = trim($template);
        $i_id = empty($i_id) ? $this->ci->inlineeditor_text_tmodel->create_i_id($template) : $i_id;

        // Create and redirect if needed
        if ($this->show_edit() && $this->ci->input->get('inline_create') == $i_id) {
            $id = $this->ci->inlineeditor_text_tmodel->add_value((empty($values) ? '' : json_encode($values)), $i_id);
            redirect($this->ci->inline_base->generate_url($id, $collection_name));
        }

        $value = $this->ci->inlineeditor_text_tmodel->get_value_by_i_id($i_id);

        $content = array_merge($values,
            !empty($value['value']) ? json_decode(htmlspecialchars_decode($value['value']), true) : []
        );

        $content['edit_btn'] = '';

        if ($this->show_edit()) {
            $url = empty($value['id']) ? '?inline_create=' . $i_id : $this->ci->inline_base->generate_url($value['id'], $collection_name);
            $content['edit_btn'] = $this->ci->inline_base->admin_link($url);
        }

        $template = str_replace('{edit_btn}', '', $template) . '{edit_btn}';

        return $this->ci->parser->parse_string($template, $content, true);
    }

    protected function show_edit()
    {
        return $this->ci->inline_base->show_edit();
    }

}