<?php

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

/**
 * Description
 *
 * @author Olexandr Vlasiuk
 */
class Rtgc_relation_translate implements Rtgc_callback
{

    protected $cache = [];
    protected $table = '';
    protected $field = '';
    protected $ci;

    public function __construct($params = [])
    {
        $this->set_params($params);
    }

    public function set_params($params = [])
    {
        if (isset($params['table']) && isset($params['field'])) {
            $this->table = $params['table'];
            $this->field = $params['field'];
            $this->ci = & get_instance();

            if (empty($this->cache[$this->table])) {
                $id_lan = $this->ci->load->library('db_lang_lib')->get_current_lang_id();
                $res = $this->ci->db->select('tt.' . $this->field . ', t.id_' . $this->table)
                                ->join($this->table . '_translate tt', 'tt.id_' . $this->table . '=t.id_' . $this->table . ' AND tt.id_lan=' . $id_lan, 'left')
                                ->get($this->table . ' t')->result_array();

                $this->cache[$this->table] = array_column($res, $this->field, 'id_' . $this->table);
            }
        }
    }

    public function init($params = [])
    {
        if (empty($params)) {
            $params = [
                'table' => $this->table,
                'field' => $this->field
            ];
        }

        return new self($params);
    }

    public function column($value = '', $data = [])
    {
        $this->check();
        
        return $this->cache[$this->table][$value];
    }

    public function field($name = '', $value = NULL)
    {
        $this->check();
        
        $this->ci->load->helper('form');

        return form_dropdown($name, $this->cache[$this->table], $value);
    }

    protected function check()
    {
        if (empty($this->table) || empty($this->field)) {
            show_error('Parametrs table and name are required');
        }

        return true;
    }

}
