<?
//$__functions['install'][]	='_autonomous_terminals_install_modul' ;
$__functions['init'][]      ='_autonomous_terminals_admin_vars' ;
$__functions['boot_site'][] ='_autonomous_terminals_site_boot' ;
$__functions['main_menu'][] ='_autonomous_terminals_main_menu' ;

function AUTONOMOUS_TERMINALS() {
    if (isset($GLOBALS['AUTONOM_MO_system'])) {
        return($GLOBALS['AUTONOM_MO_system']);
    } else {
        $GLOBALS['AUTONOM_MO_system']=new i_autonomous_terminals();
        return($GLOBALS['AUTONOM_MO_system']);
    }
}

function _autonomous_terminals_admin_vars() //
{
}

function _autonomous_terminals_install_modul($DOT_root)
{
}

function _autonomous_terminals_site_boot($options)
{
    ENGINE()->reg_ext('autonomous_terminals','Шлюз для автономных терминалов') ;
}

function _autonomous_terminals_main_menu($page)
{
    $page->menu['/cab/autonomous_terminals/upload/mo/from_file/']['title']='Автономные МО';
    $page->menu['/cab/autonomous_terminals/upload/mo/from_file/']['items']['/cab/autonomous_terminals/upload/mo/from_file/']=array('title'=>'Загрузка с автономных терминалов') ;
    $page->menu['/cab/autonomous_terminals/upload/mo/from_file/']['items']['/cab/autonomous_terminals/upload/mo/log/']=array('title'=>'Лог работы шлюза') ;
    $page->menu['/cab/autonomous_terminals/upload/mo/from_file/']['items']['/cab/autonomous_terminals/upload/mo/setting/']=array('title'=>'QR code для настройки терминалов') ;
}

class i_autonomous_terminals
{

    function __construct()
    {
    }

    function install()
    {
        $descr_class[620]['name']='Автономные медосмотры' ;
        $descr_class[620]['parent']=0 ;
        $descr_class[620]['fields']['terminal_uid']=array('type'=>'varchar(40)','index'=>'terminal_uid') ;
        $descr_class[620]['fields']['mo_session_uid']=array('type'=>'varchar(40)','index'=>'mo_session_uid') ;

        SETUP()->reg_class($descr_class) ;

        $pattern=array() ;
        $pattern['table_title']		        = 	'Автономные медосмотры' ;
        $pattern['use_clss']		        = 	'620' ;
        $pattern['table_name']				= 	'autonomous_mo' ;
        create_table_by_pattern($pattern) ;

        $apikey = substr(md5(uniqid(rand(),true)),0,15); //15 символов
        $id_sect=SETUP_add_section_to_site_setting('Автономные терминалы') ;
        SETUP_add_rec_to_site_setting($id_sect,"API KEY",$apikey,'LS_api_key_for_authorization',array('hidden'=>1)) ;
        SETUP_add_rec_to_site_setting($id_sect,"Protocol",'','LS_autonom_term_server_protocol',array('hidden'=>1)) ;
        SETUP_add_rec_to_site_setting($id_sect,"IP server",'','LS_autonom_term_server_ip',array('hidden'=>1)) ;
        SETUP_add_rec_to_site_setting($id_sect,"Port",'','LS_autonom_term_server_port',array('hidden'=>1)) ;
    }

    function update_data_from_QR_code($data)
    {
        update_site_setting('LS_autonom_term_server_protocol',$data['protocol']) ;
        update_site_setting('LS_autonom_term_server_ip',$data['server_name']) ;
        update_site_setting('LS_autonom_term_server_port',$data['port']) ;
    }

    function check_access($key)
    {
        $key = strtolower($key);
        if ($key != 'token '.$GLOBALS['LS_api_key_for_authorization']) return false;
        else return true;
    }

    //поиск терминала в МТ и КТ
    function search_terminal($rec)
    {
        $error = '';
        //ищем терминал
        $terminal_info = DEVICE()->get_terminal_by_id($rec['terminal_id']);
        $type = 'old';
        if (!$terminal_info) {
            $terminal_info = ESMO()->get_terminal_by_id($rec['terminal_id']);
        }
        //если нет - создаем
        if (!$terminal_info) {
            $result = $this->create_new_terminal($rec['terminal_id'],$rec['terminal_type']);
            if ($result['error']) {
                $error = $result['error'];
                $terminal_info = false;
            } else {
                $terminal_info = $result;
            }
            $type = 'new';
        }
        return array($terminal_info,$type,$error);
    }

    function create_new_terminal($terminal_id,$terminal_type)
    {
        $group_name = "Автономные терминалы";
        if ($terminal_type == 'kt') {
            $group_id = execSQL_value('select pkey from obj_site_skd where parent=1 and clss=600 and obj_name="'.$group_name.'"');
            if (!$group_id) {
                $data = ['name'=>$group_name,'zone_id'=>1];
                SKD()->zone_create($data);
                $group_id = execSQL_value('select pkey from obj_site_skd where parent=1 and clss=600 and obj_name="'.$group_name.'"');
            }
            $result = DEVICE()->terminal_create(['id'=>$terminal_id,'ip'=>$terminal_id,'parent'=>$group_id,'name'=>'KT '.$terminal_id,'zone_id'=>$group_id]);
        } else {
            $group_id = execSQL_value('select pkey from obj_site_account where parent=1 and clss=206 and obj_name="'.$group_name.'"');
            if (!$group_id) {
                $data = ['name'=>$group_name,'group_id'=>1];
                ACCOUNTS()->GROUP_create($data);
                $group_id = execSQL_value('select pkey from obj_site_account where parent=1 and clss=206 and obj_name="'.$group_name.'"');
            }
            $result = ESMO()->terminal_create(['id'=>$terminal_id,'ip'=>$terminal_id,'group_id'=>$group_id,'name'=>'МТ '.$terminal_id,'profil'=>1,'enabled'=>1,'terminal_type'=>$terminal_type]);
            $pkey = execSQL_value('select pkey from obj_site_account where id='.$terminal_id);
            execSQL_update('update obj_site_account set video=1, tonometer=1, thermometer=1, alcotester=1, pupilometer=1 where pkey='.$pkey);
        }
        return $result;
    }

    //ищем/создаем группу и критерий осмотра для автономных терминалов
    function rules_create()
    {
        $name = 'Автономные МО';
        //ищем группу
        $groups = PERSONAL()->get_list_groups();
        $group_id = 0;
        foreach ($groups as $group) if ($group['obj_name'] == $name) $group_id = $group['id'];
        //если нет - создаем
        if (!$group_id) {
            $res=PERSONAL()->group_create(array('obj_name'=>$name,'hidden'=>1)) ;
            $group_id = $res['id'];
        }
        $criterion = 0;
        //ищем критерий
        foreach(_IL('IL_dg')->recs as $id=>$rec) if ($rec['obj_name'] == $name) $criterion = $rec['id'];
        //если нет - создаем
        if (!$criterion) {
            $rec=$this->convert_rules_post_data_to_rec(['name'=>$name,'group'=>$group_id]) ;
            $rec['settings']=array('hidden'=>1);
            $res=_IL('IL_dg')->rec_create($rec) ;
            $criterion = $res['id'];
        }
        //возвращаем id критерия осмотра
        return $criterion;
    }

    function convert_rules_post_data_to_rec($rec_post)
    {   $rec=array() ; $title=array() ;
        if ($rec_post['age']) list($rec['age_min'],$rec['age_max'])=explode('-',$rec_post['age']) ;
        if ($rec_post['_s']) { list($rec['s_min'],$rec['s_max'])=explode('-',$rec_post['s']) ; $rec['s']=1 ; } else $rec['s']=0 ;
        if ($rec_post['_d']) { list($rec['d_min'],$rec['d_max'])=explode('-',$rec_post['d']) ; $rec['d']=1 ; } else $rec['d']=0 ;
        if ($rec_post['_t']) { list($rec['t_min'],$rec['t_max'])=explode('-',$rec_post['t']) ; $rec['t']=1 ; } else $rec['t']=0 ;
        if ($rec_post['_p']) { list($rec['p_min'],$rec['p_max'])=explode('-',$rec_post['p']) ; $rec['p']=1 ; } else $rec['p']=0 ;
        if ($rec_post['_a']) $rec['a']=1 ; else $rec['a']=0 ;
        if ($rec_post['_n']) $rec['n']=1 ; else $rec['n']=0 ;
        if ($rec_post['_v']) $rec['v']=1 ; else $rec['v']=0 ;
        if ($rec_post['name']) $rec['obj_name']=$rec_post['name'] ;
        if ($rec_post['method']) $rec['method']=$rec_post['method'] ; else $rec['method']=0 ;
        if (isset($rec_post['_esmo_groups']) and _sizeof($rec_post['_esmo_groups'])) $rec['esmo_groups']=implode(',',$rec_post['_esmo_groups']) ; else $rec['esmo_groups']='' ;
        if ($rec['age_min']) $title['age']='от '.$rec['age_min'].' лет' ;  else $rec['age_min']=0 ;
        if ($rec['age_max']) $title['age'].=' до '.$rec['age_max'].' лет' ; else $rec['age_max']=0 ;
        if (isset($rec_post['time_from'])) { if ($rec_post['time_from']!="") { $rec['time_from']=strtotime($rec_post['time_from']) ; $title['time']='c '.$rec_post['time_from'] ; }
            //else  $rec['time_from']=0 ;
        }
        if (isset($rec_post['time_to']))   { if ($rec_post['time_to']!="") {$rec['time_to']=strtotime($rec_post['time_to'].' 23:59:59'); $title['time'].=' по '.$rec_post['time_to'] ; }
            //else  $rec['time_to']=0 ;
        }
        if (isset($rec_post['working'])) { $rec['working']=$rec_post['working'] ; if ($rec_post['working']) $title[]=_IL('IL_works')->recs[$rec_post['working']]['obj_name'] ; }
        if (isset($rec_post['group'])) { $rec['group_id']=$rec_post['group'] ; if ($rec_post['group']) $title[]=_IL('IL_groups')->recs[$rec_post['group']]['obj_name'] ; }
        //$rec['obj_name']=(_sizeof($title))? implode(" \n ",$title):'Общее правило' ;

        return($rec) ;
    }

    function search_mo($rec)
    {
        $recs = execSQL_value('select pkey from autonomous_mo where terminal_uid="'.$rec['terminal_uuid'].'" and mo_session_uid="'.$rec['medexam_uuid'].'"');
        if (!$recs) {
            execSQL_update('insert into autonomous_mo (terminal_uid,mo_session_uid) value ("'.$rec['terminal_uuid'].'","'.$rec['medexam_uuid'].'")');
            return true;
        } else return false;
    }

    function import_data_xml($upload_file_name)
    {
        $result = array();
        $XML_source=file_get_contents(_DIR_TO_ROOT.$upload_file_name) ;
        $XML = new SimpleXMLElement($XML_source);
        $i=0;
        if (is_object($XML)) foreach($XML->children() as $item) {
            $test= [];
            foreach($item as $teg=>$teg_value) {
                if ($teg == 'signature') foreach($teg_value as $signature=>$signature_v) {
                    if ($signature == 'data') {
                        foreach($signature_v as $point=>$point_value) {
                            $attributes = $point_value->attributes();
                            $attr_array = (array)$attributes;
                            $attr_array = $attr_array['@attributes'];
                            $std=[];
                            foreach ($attr_array as $key=>$value) {
                                $std[$key]=(int)$value;
                            }
                            $test[] = $std;
                        }
                        $result[$i][$teg][$signature]=$test;
                    } else $result[$i][$teg][$signature] = (string)$signature_v;
                }
                else $result[$i][$teg]=(string)$teg_value;
            }
            $i++;
        }
        return $result;
    }

    function import_data_json($upload_file_name)
    {
        $result = array();
        $JSON_source=file_get_contents(_DIR_TO_ROOT.$upload_file_name) ;
        $JSON = json_decode($JSON_source,true);
        $row = 0;
        if (is_array($JSON)) {
            foreach($JSON as $item) {
                $result[$row] = $item;
                $test = [];
                if ($item['signature'] and $item['signature']['data'] and is_array($item['signature']['data'])) {
                    foreach($item['signature']['data'] as $point=>$point_value) {
                        foreach ($point_value as $key=>$value) {
                            $std[$key]=(int)$value;
                        }
                        $test[] = $std;
                    }
                    $result[$row]['signature']['data'] = $test;
                }
                $row++ ;
            }
        }
        return $result;
    }

}
?>
