<?php

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

/**
 * Description
 *
 * @author Igor Ratsun
 */
class Rtgc_textarea extends \Abstract_rtgc_callback implements \Rtgc_filtrable
{

    protected $options = array(
        'class'     => 'input-xxlarge',
        'rows'      => '10',
        'maxlength' => '512',
    );

    public function __construct($opt = array())
    {
        $this->set_options($opt);
    }

    public function column($value = '', $data = array())
    {
        return $value;
    }

    public function field($name = '', $value = NULL)
    {
        $options = $this->options;
        $options['name'] = $name;
        $options['id'] = preg_replace('/(:|\.|\[|\]|,|=|@)/', '_', $name);;

        $html = '<textarea';
        foreach ($options as $k => $v) {
            $html .= ' ' . $k . '="' . $v . '"';
        }
        $html .= ' >' . $value . '</textarea>';

        if ($this->draw_counter()) {
            $c_id = 'counter_' . $options['id'];
            get_instance()->js_css->add_js_string('$(function(){$("#' . $options['id'] . '").keyup(function(){$("#' . $c_id . '").html($(this).val().length + "/" + ' . $this->options['maxlength'] . ')}).keyup();});');
            $html .= '<div><small id="' . $c_id . '"></small></div>';
        }

        return $html;
    }

    public function set_options($opt = array())
    {
        if (is_array($opt)) {
            $this->options = array_merge($this->options, $opt);
        }

        return $this;
    }

    public function filter($name, $value)
    {
        return (new \Rtgc_input())->filter($name, $value);
    }

    public function filter_by($column, $value)
    {
        (new \Rtgc_input())->filter_by($column, $value);
    }

    /**
     * @return bool
     */
    protected function draw_counter()
    {
        return (self::class === get_class($this));
    }
}
