<?php

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

/**
 * Set price input
 *
 * @author Igor Ratsun
 */
class Rtgc_price extends \Abstract_rtgc_callback implements \Rtgc_filtrable
{

    protected $cur_aliases = [
        'uah' => '₴',
        'usd' => '$',
        'rub' => 'ք',
    ];
    protected $currency = '₴';

    public function __construct($currency = 'uah')
    {
        $this->set_currency($currency);
    }

    public function set_currency($currency = 'uah')
    {
        $this->currency = isset($this->cur_aliases[$currency]) ? $this->cur_aliases[$currency] : $currency;

        return $this;
    }

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

    public function field($name = '', $value = NULL)
    {
        $js = '$(function(){
                    $(\'.money\').keypress(function (e) {
                        if (e.which != 46 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                            return false;
                        }
                    });
                });';
        get_instance()->js_css->add_js_string($js);

        return '<div class="input-prepend"><span class="add-on">'
            . $this->currency . '</span><input class="span2 money" name="'
            . $name . '" type="text" placeholder="99.99" value="'
            . number_format(floatval($value), 2, '.', '')
            . '"></div>';
    }

    public function filter($name, $value)
    {
        return sprintf('<input type="number" name="%s" value="%s" />', $name, $value);
    }

    public function filter_by($column, $value)
    {
        if (strlen($value) == 0) {
            return;
        }
        $value = floatval(str_replace([',', ' '], '.', $value));
        get_instance()->db->where($column, $value);
    }
}
