<?php

class Inline_video_yt
{
    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, $i_id = null)
    {
        $text = trim($text);
        $i_id = empty($i_id) ? $this->ci->inlineeditor_text_tmodel->create_i_id($text) : $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('', $i_id);
            redirect($this->generate_url($id));
        }

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

        $content = [
            'src'      => str_replace('https://youtu.be/', '', (!empty($value['value']) ? $value['value'] : $text)),
            'edit_btn' => '',
        ];

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

        $template = '<div class="video_yt"><iframe src="https://www.youtube.com/embed/{src}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>{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)
    {
        return $this->ci->inline_base->generate_url($id, 'yt_video');
    }
}