<?php
include_once(_DIR_TO_CLASS.'/c_page.php') ;
class c_page_cab_poll_session extends c_page
{
 public $h1='Карточка сеанса опроса' ;
 public $page_type='window' ;
 public $rec_poll=array() ;
 public $rec_personal=array() ;

 // дополнительно передаем $poll_id через параметр, так как будет вызов страницы со станицы "карточка МО/КЗ"
 function select_obj_info($poll_id=0)
 { if (!$poll_id) $poll_id=_CUR_ID ;
   if ($poll_id)
    { $this->rec_poll=POLL()->get_poll_by_id($poll_id) ;
      if ($this->rec_poll['pkey'])
      { if ($this->rec_poll['personal_id']) $this->rec_personal=PERSONAL()->get_personal_by_id($this->rec_poll['personal_id']) ;
      }
      else $this->result=404 ;
    }
 }

 function get_cur_page_meta_tags()
 {
   if ($this->rec_personal['pkey']) $this->h1='Опрос сотрудника '.$this->rec_personal['obj_name'] ;
 }

 function panel_main_menu_title()
 {  if ($this->rec_personal['pkey']){?><li aria-haspopup="true"><a href="<?echo $this->rec_poll['__href']?>"><strong>Медицинский осмотр</strong><br>№ <?echo $this->rec_poll['pkey']?><br><?echo date('d.m.Y H:i',$this->rec_poll['c_data'])?></a></li><?}
 }


 function menu_config()
 { // вкладки для сотрудника
   if ($this->rec_poll['pkey'])
      { $this->menu[$this->rec_poll['__href']]='Карточка опроса' ;
        if ($this->rec_personal['pkey'])    $this->menu[$this->rec_personal['__href'].'?from_kz='.$this->rec_poll['pkey']]='Карточка сотрудника' ;
        if ($GLOBALS['LS_mo_logging_full']) $this->menu[$this->rec_poll['__href'].'log/']='Журнал событий' ;
        $this->menu[$this->rec_poll['__href'].'db/']='Исходные данные' ;
      }
 }

 function _second_menu_config()
  { if ($this->rec_poll['pkey'])
    { $this->second_menu[$this->rec_poll['__href']]='Карточка опроса' ;
    }
  }


 function block_main()
 {  $this->page_title() ;
    $this->panel_mo() ;
    //if ($this->rec_personal['pkey']) $this->panel_list_mo_to_member($this->rec_personal['pkey'],array('to_mo_id'=>$this->rec_poll['pkey'],'limit'=>10,'view_name'=>'obj_site_mo_session')) ;
 }

 function panel_mo()
 { $this->panel_mo_view() ;
   $this->panel_poll_view();
   $this->panel_img_kz_view();
 }


 function panel_img_kz_view()
 { ?><table id="panel_img_kz_view" reffer="<?echo $this->rec_poll['_reffer']?>"><tr><th><strong>Фото сотрудника</strong></th><th><strong>Фото при авторизации</strong></th><th><strong>Подпись сотрудника</strong></th></tr>
          <tr><td><? if ($this->rec_poll['_personal_img']) { ?><img width=200 src="<?echo $this->rec_poll['_personal_img']?>"><?}?></td>
              <td><? if ($this->rec_poll['_personal_img_auth']) {?><img width=200 src="<?echo $this->rec_poll['_personal_img_auth']?>"><?}?></td>
              <td><?echo $this->panel_sign($this->rec_poll) ;?></td>
          </tr>
      </table>
     <style type="text/css">
         table#panel_img_kz_view{width:100%;table-layout:auto;border-collapse:collapse;}
         table#panel_img_kz_view th{text-align:center;text-transform:uppercase;padding:10px 0;}
         table#panel_img_kz_view td{text-align:center;vertical-align:middle;}
         table#panel_img_kz_view td:nth-child(1){width:30%;}
         table#panel_img_kz_view td:nth-child(2){width:30%;}
         table#panel_img_kz_view td:nth-child(3){width:auto;}
         table.info.kz td{width:300px;}
         table.info.kz td:first-child{width:150px;}
     </style>
   <?
 }


function panel_mo_view()
  { $options=array() ;
    if ($this->rec_poll['group_id']) $options['esmo_group']=$this->rec_poll['group_id'] ;
    if ($this->rec_poll['terminal_id'])        $options['terminal_id']=$this->rec_poll['terminal_id'] ; // флаг МО на терминале

    ?><table class="info kz float_left">
        <tr><td>ФИО:</td><td><?echo $this->rec_poll['personal_name']?></td></tr>
        <tr><td>Дата рождения:</td><td><?echo $this->rec_poll['personal_dr']?></td></tr>
        <tr><td>UID:</td><td><?echo $this->rec_poll['personal_uid']?></td></tr>
        <tr><td>Табельный номер:</td><td><?echo $this->rec_poll['personal_tabnumber']?></td></tr>
      </table>
      <table class="info kz float_left">
        <tr><td>Организация:</td><td><?echo $this->rec_poll['_org_name']?></td></tr>
        <tr><td>Подразделение:</td><td><?echo $this->rec_poll['_otdel_name']?></td></tr>
        <tr><td>Должность:</td><td><?echo $this->rec_poll['_work_name']?></td></tr>
      </table>
     <table class="info kz float_left">
       <tr><td>Группа:</td><td colspan="2" class="left"><?echo  $this->rec_poll['group_name'] ?></td></tr>
       <tr><td>Дата опроса:</td><td><? echo date('d.m.Y H:i',$this->rec_poll['c_data']) ;
                  if ($this->rec_poll['e_data']) echo ' - '.date('H:i',$this->rec_poll['e_data']) ;
               ?>
               <?if ($this->rec_poll['_term_cam_1'] or $this->rec_poll['video']){?>&nbsp;<span class="v2" cmd="media_server/get_video_from_terminal" id_mo="<?echo $this->rec_poll['pkey']?>"><i class="fa fa-video-camera"></i></span><?}?>
           </td>
       </tr>
       <?if ($this->rec_poll['terminal_comment'])
       { ?><tr><td>Сообщение на терминале:</td>
                  <td colspan="2" class="left"><span class="big green"><?echo $this->rec_poll['terminal_comment']?></span></td>
           </tr><?

       }
      if ($GLOBALS['LS_mo_auth_by_photo'] and stripos('intrusion',$this->rec_poll['reason'])!==false)
             { ?><tr>
                     <td></td>
                     <td colspan="2" class="left red bold">Требуется подтверждение личности сотрудника
                         <?
                         if (   ( $this->rec_poll['status']==2 // сеанс МО завершен успешно (МО пройден)
                             and !$this->rec_poll['dopusk']   // допуска нет
                             and (($GLOBALS['LS_setting_auto_dopuck'] and stripos('intrusion',$this->rec_poll['reason'])!==false) // допуск ставиться автоматически, но требуется подтверждение личности
                             )
                         )
                         )
                         {   ?>&nbsp;&nbsp;<button class="v2 button_green" cmd="aspmo_mo/mo_dopusk_allow" mo_id="<?echo $this->rec_poll['pkey']?>">Допустить</button><?
                             ?>&nbsp;&nbsp;<button class="v2 button_red" cmd="aspmo_mo/hand_dopusk_clear" mo_id="<?echo $this->rec_poll['pkey']?>">Аннулировать опрос</button><?
                         }


                         ?>
                     </td>
                 </tr>
                 <?
             }

         if ($this->rec_poll['terminal_id'])
         {?><tr><td>Терминал:</td><td><? echo $this->rec_poll['terminal_name'].' ['.$this->rec_poll['terminal_id'].']' ;?></td></tr>
            <tr><td>Статус проверки:</td><td>
                     <? echo '<div class=mo_status_'.$this->rec_poll['status'].'>'.$this->rec_poll['_status_name'].'</div>' ;
                        if ($this->rec_poll['reason'])                      echo '<div class=red>'.$this->rec_poll['_reason'].'</div>' ;
                        if ($this->rec_poll['equipment'])                   echo '<div class=red>'.$this->rec_poll['_equipment'].'</div>' ;
                        if ($this->rec_poll['question_comment'])            echo '<div class=red>'.$this->rec_poll['question_comment'].'</div>' ;
                        if ($this->rec_poll['comment'])                     echo '<div class=red>'.$this->rec_poll['comment'].'</div>' ;
                     ?>
                 </td>
             </tr><?
          }
         if ($this->rec_poll['mo_id']){?><tr><td>МО:</td><td><? echo $this->rec_poll['mo_id']?></td></tr><?}
        ?></table>
      <div class="clear"></div>
      <?
  }
  function panel_poll_view()
{       ?><h3>Результаты опроса</h3><?

        $list_recs=execSQL('select t1.pkey as poll_pkey,t1.c_data as poll_data,t1.poll_id,t1.mo_id,t1.event_id,t1.question_id,
                        t5.pkey as theme_id,
                        t2.*,
                        t3.obj_name as question_text,
                        t5.obj_name as theme_name,
                        t4.pkey as rasdel_id,t4.obj_name as rasdel_name,
                        t7.obj_name as event_name, 
                        t8.obj_name as answer_text 
                        from  poll_result t1
                        left join '.MEMBER()->personal_viewer_name.' pvn on pvn.pkey=t1.personal_id    
                        left join view_personals t2 on t2.pkey=t1.personal_id
                        left join poll_questions t3 on t3.pkey=t1.question_id 
                        left join poll_themes t4 on t4.pkey=t3.parent 
                        left join poll_themes t5 on t5.pkey=t4.parent2 
                        left join obj_site_events_schedule t7 on t7.pkey=t1.event_id
                        left join poll_answers t8 on t8.pkey=t1.answer_id
                         
                        where  poll_id='.$this->rec_poll['pkey']) ;

        $recs_quiestion=execSQL('select * from poll_sessions_questions where parent='.$this->rec_poll['pkey'].' order by pkey') ;
        $recs_answers=execSQL('select * from poll_result where poll_id='.$this->rec_poll['pkey'].' order by pkey desc') ;
        $question_ids=array() ;
        if (_sizeof($recs_answers)) foreach($recs_answers as $rec) $question_ids[$rec['question_id']]=$rec['correct'] ;
        if (_sizeof($question_ids)) $recs=execSQL('select * from poll_questions where pkey in ('.implode(',',array_keys($question_ids)).')') ;
        if (_sizeof($recs)) $recs_answers=execSQL('select * from poll_answers where question_id in ('.implode(',',array_keys($recs)).')') ;
        if (_sizeof($recs)) $recs_contents=execSQL('select * from poll_content where question_id in ('.implode(',',array_keys($recs)).')') ;
        $recs_answers_by_question=group_by_field('question_id',$recs_answers) ;
        $recs_contents_by_question=group_by_field('question_id',$recs_contents) ;
        ?><table class="basic fz_small full auto">
            <tr>
                <th>ID результата</th>
                <th>ID билета</th>
                <th>Тема</th>
                <th>Вопрос</th>
                <th>Фото/Видео контент</th>
                <th>Ответы</th>
                <th>Выбранный ответ</th>
            </tr><?
              if (_sizeof($list_recs)) foreach($list_recs as $rec)
              {   $rec_rasdel=POLL()->get_theme_by_id($rec['rasdel_id']) ;
                  $arr=TREE('poll_themes')->get_arr_parents_names($rec_rasdel['pkey'],array('from_level'=>2)) ;
                  ?><tr>
                      <td><?echo $rec['pkey']?></td>
                      <td><?echo $rec['question_id']?></td>
                      <td class="left"><?echo implode(' / ',$arr)?></td>
                      <td class="left"><?echo $rec['question_text']?></td>
                      <td><? if (_sizeof($recs_contents_by_question[$rec['question_id']])) foreach($recs_contents_by_question[$rec['pkey']] as $rec_content)
                      { switch($rec_content['type'])
                        { case 'image/jpeg': ?><img src="<?echo $rec_content['dir'].$rec_content['file_name']?>" width="150px"><? break ;

                        }
                        //print_r($rec_content) ; echo '<br>' ;
                       }
                       ?></td>
                       <td class="left"><ul><? if (_sizeof($recs_answers_by_question[$rec['question_id']])) foreach($recs_answers_by_question[$rec['question_id']] as $rec_answer) {?><li><?echo $rec_answer['obj_name']?></li><?}?></ul></td>
                       <td style="font-size:16px;"><?echo $rec['answer_text']?></td>
                  </tr><?
              }
      ?></table><br><br><?


  }

  function panel_sign($rec)
  {
      if ($rec['DTW_id']) $DTW_id=$rec['DTW_id'] ;
      else if($rec['mo_id']) $DTW_id=execSQL_value('select pkey from obj_site_mo_session_DTW where mo_id='.$rec['mo_id'].' limit 1') ; // получение данных по старой схеме
      else $DTW_id=execSQL_value('select pkey from obj_site_mo_session_DTW where parent='.$rec['pkey'].' and poll_id=0 limit 1') ; // получение данных по старой схеме
      if ($DTW_id) // вывод подписи только для записей с id подписи
      {   $script_name=  signature()->save_DTW_data_to_js_by_id($DTW_id) ;
          if ($script_name!='no_DWT_data')
          {?><SCRIPT type="text/javascript" src="/temp/<?echo $script_name?>"></SCRIPT>
            <SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/aspmo_signature/signature_renderer.js" ></SCRIPT><?
              ?>Подпись сотрудника (DWT): <button onclick="$j('#canvas1').signatureRender(sample1);">Обновить</button><br><br>
                  <canvas id="canvas1" style="border: medium; border-color: #DBDBDB; border-style: solid;" width="600" height="400"> &nbsp; </canvas>
                  <script type="text/javascript">
                      $j(document).ready(function(){$j('#canvas1').signatureRender(sample1);});
                  </script>
               <?
          }
          else  // вывод картинку подписи, DTW уже удален
          {   $img_url=ESMO()->get_mo_DTW_img_dir_by_id($rec['pkey'],'relative') ;
              ?>Подпись сотрудника (PNG):<br>
                <img src="<?echo $img_url?>" style="margin:10px;border: medium; border-color: #DBDBDB; border-style: solid;padding:50px;">
              <?
          }
      }
  }

  function panel_list_mo_to_member($personal_id,$options=array())
  { ?><div id="panel_list_mo_to_member"><h2>Предыдущие проверки опросы сотрудника <?if ($options['limit']) echo '<span class="small">последние '.$options['limit'].' МО</span>'?></h2><label>Показывать только успешные допуски к МО <input type="checkbox" name="view_only_success" class=v2 cmd=aspmo/set_view_only_success <?if ($GLOBALS['LS_setting_mo_pers_view_only_success']) echo 'checked'?>></label><?
    //if ($member->info['rol']>1)  $options['doctor_id']=$member->id ; // только с терминалов своей группы
    if (!is_array($options)) $options=array() ;
    $options['only_check_success']=$GLOBALS['LS_setting_mo_pers_view_only_success'] ;
    $recs=ESMO()->get_mo_recs_to_personal($personal_id,$options) ;
    print_template($recs,'aspmo/list_mo_sessions_small') ;
    ?></div><?
  }

}

?>
