<?php

class Inline_text
{
    private $ci;
    private $show_edit = null;
    private $admin_segment = 'text';

    public function __construct()
    {
        $this->ci = get_instance();
        $this->ci->load->model('inlineeditor/inlineeditor_text_tmodel');
        $this->ci->js_css->parse_css('inlineeditor/css/inline.css');
    }

    public function parse($text)
    {
        $text = trim($text);
        $i_id = $this->ci->inlineeditor_text_tmodel->create_i_id($text);

        // 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($text);
            redirect($this->generate_url($id));
        }

        $value = $this->ci->inlineeditor_text_tmodel->get_value_by_i_id($i_id);
        $result = !empty($value['value']) ? $value['value'] : $text;

        if ($this->show_edit()) {
            $url = empty($value['id']) ? '?inline_create=' . $i_id : $this->generate_url($value['id']);
            $result .= $this->admin_link($url);
        }

        return $result;
    }

    public function set_admin_segment($admin_segment)
    {
        $this->admin_segment = $admin_segment;
        return $this;
    }

    protected function show_edit()
    {
        if (is_null($this->show_edit)) {
            $this->ci->load->library(['ciext/configurator', 'ciext/RT_user']);
            // Access check
            if (!$this->ci->rt_user->isAllowed('inlineeditor', 'edit_inlineeditor')) {
                $this->show_edit = false;
                return $this->show_edit;
            }
            $cnf = new configurator('inlineeditor');
            $this->show_edit = !empty($cnf->item('show_editor'));
        }

        return $this->show_edit;
    }

    protected function admin_link($url)
    {
        return '<a href="' . $url . '" class="inline_edit_link"><i class="fa fa-edit"></i> ' . $this->ci->lang->line('Edit') . '</a>';
    }

    protected function generate_url($id)
    {
        return base_url($this->ci->config->item('admin_page'))
            . '/mconfig/index/inlineeditor/inline/'
            . $this->admin_segment . '/edit/' . $id
            . '?referer=' . base_url($this->ci->uri->uri_string());
    }
}