<?php

class Inline_img
{
    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($text, $attributes = [], $i_id = null)
    {
        $text = trim($text);
        $i_id = empty($i_id) ? $this->ci->inlineeditor_text_tmodel->create_i_id($text) : $i_id;
        $width = 0;
        $height = 0;

        if (!empty($attributes['width'])) {
            $width = $attributes['width'];
            unset($attributes['width']);
        }
        if (!empty($attributes['height'])) {
            $height = $attributes['height'];
            unset($attributes['height']);
        }

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

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

        $content = [
            'src' => !empty($value['value']) ? '/assets/uploads/multimedia/images/' . $value['value'] : $text,
            'edit_btn' => '',
        ];

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

        if (empty($attributes['alt'])) {
            $attributes['alt'] = '';
        }

        $template = '<div class="img_container"><img src="{src}"';
        foreach ($attributes as $k => $v) {
            $template .= ' ' . $k . '="' . $v . '"';
        }
        $template .= '/>{edit_btn}</div>';

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

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

    protected function generate_url($id)
    {
        $url = $this->ci->inline_base->generate_url($id, 'img');
        if (!empty($this->ci->input->get('width')) && !empty($this->ci->input->get('height'))) {
            $url .= '&width=' . (int) $this->ci->input->get('width') . '&height=' . (int) $this->ci->input->get('height');
        }
        return $url;
    }
}