<?php

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

/**
 * Description of configuration_model
 *
 * @author Igor Ratsun
 */
class Configuration_model extends \Ciext\Model\AbstractEventModel
{

    public function get_languages()
    {
        $data = $this->db->
                        select('id_lan, name, active')->
                        get('lan')->result_array();

        foreach ($data as &$v) {
            $v['active'] = ($v['active']) ? 'active' : '';
        }
        unset($v);

        return $data;
    }

    public function upd_lang($id_lan, $active)
    {
        $this->db->update('lan', ['active' => intval($active)], ['id_lan' => intval($id_lan)]);
        $affected_rows = $this->db->affected_rows();

        // Update 
        if (!empty($active)) {
            // Add resmng data
            $this->add_res('resource_type_page_data', $id_lan, 'id_resource_type_page', ['seo_title', 'seo_keywords', 'seo_description']);
            $this->add_res('resource_type_page_template_translate', $id_lan, 'id_resource_type_page_template', ['content']);
            $this->add_res('resource_type_resource_translate', $id_lan, 'id_resource_type_resource', ['content']);
        }

        $this->notify(__FUNCTION__, [
            'id_lan'        => $id_lan,
            'active'        => $active,
            'affected_rows' => $affected_rows
        ]);

        return $affected_rows;
    }

    protected function add_res($table, $id_lan, $main_key, $ins_keys)
    {
        $current = $this->db->select($main_key . ', id_lan')->where('id_lan', $id_lan)->get($table)->result_array();
        $src_lang_id = $this->load->library('db_lang_lib')->get_current_lang_id();
        $src = $this->db->where('id_lan', $src_lang_id)->get($table)->result_array();

        if (count($current) == count($src)) {

            return true;
        }

        $prepared_current = [];
        foreach ($current as $item) {
            $prepared_current[$item[$main_key] . '_' . $item['id_lan']] = $item;
        }

        foreach ($src as $item) {
            if (isset($prepared_current[$item[$main_key] . '_' . $item['id_lan']])) {
                continue;
            }
            $insert = [
                $main_key => $item[$main_key],
                'id_lan'  => $id_lan,
            ];
            foreach ($ins_keys as $ins_key) {
                $insert[$ins_key] = $item[$ins_key];
            }
            $this->db->insert($table, $insert);
        }

        return true;
    }

}
