<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Description of Inlineeditor_text_tmodel
 *
 * @author CIEXT skeleton
 */
class Inlineeditor_text_tmodel extends \Ciext\Model\AbstractTableModel
{

    protected $table = 'inlineeditor_text';
    protected $pkey = 'id_inlineeditor_text';
    private $page_id;
    private $lang_id;
    private $cache = [];

    public function __construct()
    {
        parent::__construct();

        $this->load->model('ciext/core_model');
        $this->page_id = $this->core_model->get_current_page_id();
        $this->lang_id = $this->core_model->get_lang_id();
    }

    public function create_i_id($text)
    {
        return md5($text);
    }

    public function add_value($value)
    {
        return parent::add([
            'i_id'                  => $this->create_i_id($value),
            'value'                 => $value,
            'id_resource_type_page' => $this->page_id,
            'id_lan '               => $this->lang_id,
        ]);
    }

    public function fetch_all_current()
    {
        if (empty($this->cache)) {
            $data = $this->set_predicates([
                'id_resource_type_page' => $this->page_id,
                'id_lan '               => $this->lang_id
            ])->set_select('t.i_id, t.value, t.id_inlineeditor_text as id')->fetch_all();
            foreach ($data as $item) {
                $this->cache[$item['i_id']] = $item;
            }
        }

        $this->notify(__FUNCTION__, $this->cache);

        return $this->cache;
    }

    public function get_value_by_i_id($i_id)
    {
        if (empty($this->cache[$i_id])) {
            $this->cache = $this->fetch_all_current();
        }

        return !empty($this->cache[$i_id]) ? $this->cache[$i_id] : '';
    }
}
