<?php
include_once(_DIR_TO_CLASS."/c_page.php");
class c_page_term extends c_page
{
 public $h1='Эмулятор терминала' ;
 public $terminal_id=0 ;
 public $rec_term=array() ;
 public $page_type='window' ;
 public $free_access=1 ;
 public $rec_terminal=array() ;
 public $menu_show_account_item=1 ;

 function set_head_tags()
 {  parent::set_head_tags() ;
    $this->HEAD['css'][]='/'._CLASS_.'/assets/mForm.css' ;
 }

 function menu_config()
 {

     //damp_array($this);

     //damp_string($this->rec_terminal) ;
    if (!$this->rec_terminal['pkey'])  $this->menu['/term/']=array('title'=>'Вирт. терминалы','class'=>'fa fa-user-md') ;
    if ($this->rec_terminal['pkey'] and $this->rec_terminal['terminal_type']=='mt') $this->menu['/term/'.$this->terminal_id.'/']=array('title'=>'МО','class'=>'fa fa-user-md') ;
    if ($this->rec_terminal['pkey'] and $this->rec_terminal['terminal_type']=='kt') $this->menu['/term/'.$this->terminal_id.'/kt/']=array('title'=>'Контроль трезовсти','class'=>'fa fa-user-md') ;
    if ($this->rec_terminal['pkey'] and $this->rec_terminal['terminal_type']=='kz')
    { $this->menu['/term/'.$this->terminal_id.'/kz/']=array('title'=>'Контроль знаний','class'=>'fa fa-user-md') ;
    }
    //$this->menu['/term/'.$this->terminal_id.'/kt/']=array('title'=>'KT','class'=>'fa fa-user-md') ;
    //$this->menu['/term/'.$this->terminal_id.'/whois/']=array('title'=>'WHOIS','class'=>'fa fa-user-md') ;
    //$this->menu['/term/'.$this->terminal_id.'/SSE/']=array('title'=>'Проверка','class'=>'fa fa-user-md') ;


 }

 function select_obj_info()
 { if (_CUR_ID)
   { $this->rec_terminal=DEVICE()->get_terminal_by_id(_CUR_ID,array('debug'=>0)) ;
     $this->terminal_id=$this->rec_terminal['id'] ;
   }
 }

 function check_access() {return(1);}
 function member_menu_check(&$menum,$options=array()) {}



  function panel_main_menu_title()
  { ?><li aria-haspopup="true"><a><strong>Терминал № <?echo $this->terminal_id?></strong></a></li><?
  }

  function block_main()
  {   // удаляем виртуальные терминалы, по ID совпадающие с реальными терминалами
      $term_ids=execSQL_line('select id from obj_site_account where clss=203 and (virt=0 or virt is null) and id>0') ;
      if (_sizeof($term_ids)) execSQL_update('delete from obj_site_account where clss=203 and virt=1 and id in ('.implode(',',$term_ids).' ) ') ;
      //execSQL('select * from obj_site_account where clss=203 and id=100',2) ;

      if (!_CUR_ID) $this->panel_vterms() ;
      else if (!$this->terminal_id) $this->panel_terminal_register() ;
      else if (!$this->rec_terminal['virt']) echo 'Указан ID боевого терминала<br> <button class="v1" href="/term/">Перейти к списку виртуальных терминалов</button>' ;
      else
      {   switch($this->rec_terminal['terminal_type'])
          { case 'mt': $this->panel_mt() ; break ;
            case 'kz': $this->panel_mt() ; break ;
            case 'kt': $this->panel_kt() ; break ;
            default: echo 'Для данного типа терминала ('.$this->rec_terminal['terminal_type'].') панель не определена' ;
          }
      }

  }

  function panel_terminal_register()
  {   $term_types=array('mt'=>'Медицинский терминал','kt'=>'Терминал контроля трезвости','kz'=>'Терминал контроля знаний') ;
      ?><div id="panel_select_group"><form>
                <h2>Терминал <?echo _CUR_ID?> не зарегистрирован в системе. Выберите рабочую группу для регистрации терминала.</h2><?
                $groups=ACCOUNTS()->get_list_workgoups(array('usl'=>'clss in (1,206) and enabled=1')) ;
                ?><strong>Рабочая группа: </strong>
                 <select name="use_group" data-select><option></option><?if (_sizeof($groups)) foreach($groups as $rec){?><option value="<?echo $rec['pkey']?>"><?echo $rec['obj_name']?></option><?}?></select>
                 <select name="term_type" data-select><?if (_sizeof($term_types)) foreach($term_types as $id=>$title){?><option value="<?echo $id?>"><?echo $title?></option><?}?></select>
                 <input type=submit class="v2" cmd="aspmo_term/register_vterm" validate=form terminal_id="<?echo _CUR_ID?>" value="Зарегистрировать">
                </form></div><div id=panel_message></div><?
  }

  function panel_vterms()
  { $recs=ESMO()->get_list_terminals(-1,'','t1.virt=1') ;

    ?><h2>Список виртуальных терминалов:</h2><br>
    <form><input type="text" name="count_terminal" value="1" style="width:40px;">
          <button class="v2" cmd="aspmo_term/create_vterm">Добавить виртуальные терминалы</button>
          <button class="v2" cmd="aspmo_term/start_auto">START AUTO</button>
          <button class="v2" cmd="aspmo_term/stop_auto">STOP AUTO</button>

    </form><?php
    include_once(_DIR_EXT.'/esmo_setting/panel_terminals.php')  ;
    if (_sizeof($recs)) panel_terminals($recs,array('no_fast_search'=>1,'no_panel_actions'=>1,'term_page'=>'')) ;
    else echo '<div class=alert>В данной рабочей группе терминалы отстутсвуют. Воспользуйтесь конфигуратором системы для добавления терминалов в группу.</div>' ;

    if (_sizeof($recs)){?><br><button class="v2" cmd="aspmo_term/delete_all_vterm">Удалить все виртуальные терминалы</button><?}
  }


   function convert_tree_to_select_options_arr($arr_tree,&$recs,&$options_list,$level=0)
       {  $pref=($level)? str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$level-1).'|--':"" ;
          $level++ ;
          if (_sizeof($arr_tree)) foreach ($arr_tree as $id=>$arr_childs)
          {   $options_list[$id]=$pref.$recs[$id]['obj_name'] ;
              if (_sizeof($arr_childs)) $this->convert_tree_to_select_options_arr($arr_childs,$recs,$options_list,$level) ;
          }
       }



  function panel_mt()
  {
      $this->rec_terminal=DEVICE()->get_terminal_by_id($this->terminal_id) ;
      $status=($this->rec_terminal['virt_status'])? ' [auto]':'' ;
      //damp_array($this->rec_terminal) ;

      $this->page_title('Эмулятор медицинского терминала № '.$this->terminal_id.$status) ;


      if ($this->rec_terminal)
      { $recs_term[]=$this->rec_terminal ;
        include_once(_DIR_EXT.'/esmo_setting/panel_terminals.php')  ;
        panel_terminals($recs_term,array('no_fast_search'=>1,'no_panel_actions'=>1,'no_panel_group'=>1,'term_page'=>'')) ;


          //update_rec_in_table('obj_site_account',array('status'=>2),'pkey='.$rec['pkey']) ;
         //if (!$this->rec_terminal['virt_status'])
         { ?>&nbsp;&nbsp;
             <br>

           <?
     $arr_accounts=ACCOUNTS()->get_list_members(array('rol'=>'2,3','no_filter_by_cur_group'=>1)) ;
     $arr_groups=ACCOUNTS()->get_arr_tree_workgroups() ;

     $this->form->filter['group_id']=$this->rec_terminal['parent'] ;
     $this->form->filter['doctor_id']=ESMO()->check_doctor($this->rec_terminal['parent']) ;
     $this->form->filter['profil_id']=$this->rec_terminal['profil'] ;

     echo 'fix_pass='.$_SESSION['virt_term']['fix_pass'].'<br>' ;
     ?><div id="panel_filter">
       <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo $this->url_report?>">
            <fieldset>
                <div class="row">
                    <? $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups,array('nospace_element'=>1)) ;
                       $this->filter_section_select('doctor_id','Фельдшер:',2,$arr_accounts,array('nospace_element'=>1)) ;
                       $this->filter_section_select('profil_id','Профиль терминала:',2,_IL('IL_term_prof')->recs,array('nospace_element'=>1)) ;
                       $this->filter_section_input_text('propusk','Номер пропуска:',2) ;
                       $this->section_checkbox(['name'=>'filter[fix_pass]','title'=>'Зафиксировать пропуск:','col_count'=>2,'cmd'=>'aspmo_term/fixed_pass','cur_value'=>($_SESSION['virt_term']['fix_pass'])? 1:0]) ;

                    ?>
                </div>
            </fieldset>
            <div id="panel_buttons" style="">
                <input type="submit" id=send_propusk class="button v2" cmd="aspmo_term/send_check_access" terminal_id="<?echo $this->terminal_id?>" value="Отправить">
                <button class="button v1" update_page=1 id="reset">Reset</button>&nbsp;&nbsp;
                <button class="button v2" cmd="aspmo_term/send_power_on" terminal_id=<?echo $this->terminal_id?>>Power ON</button>&nbsp;&nbsp;
                <button class="button v2" cmd="aspmo_term/send_disinfection_complete" terminal_id=<?echo $this->terminal_id?>>Disinfection complete</button>&nbsp;&nbsp;
                <button class="button v2" cmd="aspmo_term/send_ping" terminal_id=<?echo $this->terminal_id?>>Ping</button>&nbsp;&nbsp;
                 <? if ($this->rec_terminal['virt_status']==0){?><button class="button v2" cmd="aspmo_term/start_auto" terminal_id=<?echo $this->terminal_id?>>Start Auto</button>&nbsp;&nbsp;<?}?>
                 <? if ($this->rec_terminal['virt_status']==1){?><button class="button v2" cmd="aspmo_term/stop_auto" terminal_id=<?echo $this->terminal_id?>>Stop Auto</button>&nbsp;&nbsp;<?}?>
                 <? if ($this->rec_terminal['virt_status']==2){?><button class="button v2" cmd="aspmo_term/stop_auto" terminal_id=<?echo $this->terminal_id?>>Stop Auto</button>&nbsp;&nbsp;<?}?>
            </div>
        </form>
    <?
    //echo 'virt_status='.$this->rec_terminal['virt_status'].'<br>' ;
    ?>
       </div>
             <div id="panel_message"></div>
           <?
         }
         if ($this->rec_terminal['virt_status']==1) $this->get_propusk_and_send() ;
         else
         {
             ?><script type="text/javascript">$j(document).ready(function()
                {
                    ///$j('body').everyTime('1s',function(){send_ajax_request({cmd:'aspmo_term/check_auto_mode',terminal_id:<?echo $this->rec_terminal['id']?>})},0) ;

                }) ;
               </script>
             <?
         }
      }
      else
      {
      }

      if (!$this->rec_terminal['virt_status']) // если статус = 2 и не авто режим - обновлям каждые 1 мин
       { ?><script type="text/javascript">$j(document).ready(function()
         { //$j('body').everyTime(60000,'check_status',function(){send_ajax_request({cmd:'aspmo_term/check_status_and_update',terminal_id:<?echo $this->terminal_id?>})})
         }) ;
         </script><?
       }

      $this->panel_debug() ;
  }

  function get_propusk_and_send()
  {
       // получаем случайный пропуск, из тех что сейчас не проходят МО, вписываем его в input, имитируем нажатие клавиши
       $t=getdate() ;
       $check_from=mktime($t['hours'],$t['minutes']-5,0,$t['mon'],$t['mday'],$t['year']);
       $exists_ids=execSQL_line('select member_id from obj_site_mo_session where status=1 and c_data>'.$check_from) ;
       $_usl=[];
       $_usl[]='clss=211 and enabled=1' ;
       if (_sizeof($exists_ids)) $_usl[]='not pkey in ('.implode($exists_ids).')' ;
       $usl_select=implode(' and ',$_usl) ;
       $propusk=execSQL_value('select propusk from obj_site_personals where '.$usl_select.' order by rand() limit 1') ;
       if ($propusk)
       { ?><script type="text/javascript">$j(document).ready(function()
           { $j('input[name="filter[propusk]"]').val('<?echo $propusk?>') ;
             $j('body').oneTime(3000,'timer_submit',function(){$j('input#send_propusk').trigger('click') ;})
           }) ;
         </script><?
       }
       else // иначе просто перегружаем страницк
        { ?><script type="text/javascript">$j(document).ready(function()
           {
               $j('body').oneTime(3000,'timer_reload',function(){location.reload()}) ;
           }) ;
         </script><?
         }
  }

  function panel_kt()
  {


      //  присваимваем терминалу тип - mt
      execSQL_update('update obj_site_account set terminal_type="mt" where pkey='.$this->terminal_id.' and clss=203') ;

      $this->rec_terminal=ESMO()->get_terminal_by_id($this->terminal_id) ;
      $status=($this->rec_terminal['virt_status'])? ' [auto]':'' ;
      //damp_array($this->rec_terminal) ;

      $this->page_title('Эмулятор терминала контроля трезвости № '.$this->terminal_id.$status) ;


      if ($this->rec_terminal)
      {  //update_rec_in_table('obj_site_account',array('status'=>2),'pkey='.$rec['pkey']) ;
         //if (!$this->rec_terminal['virt_status'])
         { ?><button class="v1" update_page=1 id="reset">Reset</button>&nbsp;&nbsp;
             <button class="v2" cmd="aspmo_term/send_power_on" terminal_id=<?echo $this->terminal_id?>>Power ON</button>&nbsp;&nbsp;
             <button class="v2" cmd="aspmo_term/send_ping" terminal_id=<?echo $this->terminal_id?>>Ping</button>&nbsp;&nbsp;

           <?
           if ($this->rec_terminal['virt_status']==0){?><button class="v2" cmd="aspmo_term/start_auto" terminal_id=<?echo $this->terminal_id?>>Start Auto</button>&nbsp;&nbsp;<?}
           if ($this->rec_terminal['virt_status']==1){?><button class="v2" cmd="aspmo_term/stop_auto" terminal_id=<?echo $this->terminal_id?>>Stop Auto</button>&nbsp;&nbsp;<?}
           if ($this->rec_terminal['virt_status']==2){?><button class="v2" cmd="aspmo_term/stop_auto" terminal_id=<?echo $this->terminal_id?>>Stop Auto</button>&nbsp;&nbsp;<?}
           ?><button class="v2" cmd="aspmo_term/new_terminal_window" terminal_id=<?echo $this->terminal_id?>>New Terminal</button>&nbsp;&nbsp;
             <br>
             <div id="panel_message">
                  <h2>Имитация проведения осмотра</h2>
                  <h3>Рабочая группа "<?echo ACCOUNTS()->get_group_name($this->rec_terminal['parent'])?>"</h3>
                  <div><form><input type="text" placeholder="Номер пропуска" name="user" data-required> <input id=submit type="submit" class="v2" cmd="aspmo_term/send_propusk_info" validate="form" terminal_id=<?echo $this->terminal_id?> value="Приложить пропуск к считывателю"></form></div>
             </div>
           <?
         }
         if ($this->rec_terminal['virt_status']) $this->get_propusk_and_send() ;

      }
      else
      { ?><div id="panel_select_group"><form>
          <h2>Терминал не зарегистрирован в системе. Выберите рабочую группу для регистрации терминала.</h2><?
          $groups=ACCOUNTS()->get_list_workgoups() ;
          ?><strong>Рабочая группа: </strong><select name="use_group" data-select><option></option><?if (_sizeof($groups)) foreach($groups as $rec){?><option value="<?echo $rec['pkey']?>"><?echo $rec['obj_name']?></option><?}?></select> <input type=submit class="v2" cmd="aspmo_term/register_vterm" validate=form terminal_id="<?echo $this->terminal_id?>" value="Зарегистрировать">
          </form></div><div id=panel_message></div><?
      }

      if (!$this->rec_terminal['virt_status']) // если статус = 2 и не авто режим - обновлям каждые 1 мин
       { ?><script type="text/javascript">$j(document).ready(function()
         { //$j('body').everyTime(60000,'check_status',function(){send_ajax_request({cmd:'aspmo_term/check_status_and_update',terminal_id:<?echo $this->terminal_id?>})})
         }) ;
         </script><?
       }

      $this->panel_debug() ;
  }

  function panel_debug() {?><div id="panel_debug"></div><?}


}



?>
