<?php

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

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

    protected $table = 'translate';
    protected $pkey = 'id_translate';

    public function fetch_all_by_lang_id($id_lan = 0)
    {
        if (empty($id_lan)) {
            $id_lan = $this->load->library('db_lang_lib')->get_current_lang_id();
        }

        $this->db->join('translate_value tv', '(tv.id_translate=t.id_translate AND tv.id_lan=' . (int) $id_lan . ')', 'left');

        return $this->set_select('t.id_translate, t.line, tv.value')->fetch_all();
    }

    public function save_batch($lines, $ids, $values, $id_lan)
    {
        $saved = 0;
        foreach ($ids as $key => $id_translate) {
            if ($this->save($lines[$key], $id_translate, $values[$key], $id_lan)) {
                $saved++;
            }
        }

        return $saved;
    }

    public function save($line, $id, $value, $id_lan)
    {
        if (empty($line) || empty($value)) {

            return false;
        }
        if (empty($id)) {
            $id = $this->add(['line' => $line]);
        }

        $where = [
            'id_translate' => $id,
            'id_lan'       => $id_lan
        ];
        $this->db->where($where)->replace('translate_value', array_merge($where, ['value' => $value]));

        return true;
    }

}
