<?php
include_once(_DIR_TO_CLASS.'/c_page.php') ;
class c_page_cab_quiz_kz extends c_page
{
 public $h1='Карточка сеанса контроля знаний' ;
 public $page_type='window' ;
 public $rec_kz=array() ;
 public $rec_personal=array() ;

 // дополнительно передаем $quiz_id через параметр, так как будет вызов страницы со станицы "карточка МО/КЗ"
 function select_obj_info($quiz_id=0)
 { if (!$quiz_id) $quiz_id=_CUR_ID ;
   if ($quiz_id)
    { $this->rec_kz=QUIZ()->get_quiz_by_id($quiz_id) ;
      if ($this->rec_kz['pkey'])
      { if ($this->rec_kz['personal_id']) $this->rec_personal=PERSONAL()->get_personal_by_id($this->rec_kz['rec_kz']) ;
      }
      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_kz['__href']?>"><strong>Медицинский осмотр</strong><br>№ <?echo $this->rec_kz['pkey']?><br><?echo date('d.m.Y H:i',$this->rec_kz['c_data'])?></a></li><?}
 }


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

 function _second_menu_config()
  { if ($this->rec_kz['pkey'])
    { $this->second_menu[$this->rec_kz['__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_kz['pkey'],'limit'=>10,'view_name'=>'obj_site_mo_session')) ;
 }

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


 function panel_img_kz_view()
 { ?><table id="panel_img_kz_view" reffer="<?echo $this->rec_kz['_reffer']?>"><tr><th><strong>Фото сотрудника</strong></th><th><strong>Фото при авторизации</strong></th><th><strong>Подпись сотрудника</strong></th></tr>
          <tr><td><? if ($this->rec_kz['_personal_img']) { ?><img width=200 src="<?echo $this->rec_kz['_personal_img']?>"><?}?></td>
              <td><? if ($this->rec_kz['_personal_img_auth']) {?><img width=200 src="<?echo $this->rec_kz['_personal_img_auth']?>"><?}?></td>
              <td><?echo $this->panel_sign($this->rec_kz) ;?></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_kz['group_id']) $options['esmo_group']=$this->rec_kz['group_id'] ;
    if ($this->rec_kz['terminal_id'])        $options['terminal_id']=$this->rec_kz['terminal_id'] ; // флаг МО на терминале

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

               echo  $this->rec_kz['_reader']


               ?></td></tr>

       <?if ($this->rec_kz['terminal_comment'])
       { ?><tr><td>Сообщение на терминале:</td>
                  <td colspan="2" class="left"><span class="big green"><?echo $this->rec_kz['terminal_comment']?></span></td>
           </tr><?

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


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

         if ($this->rec_kz['terminal_id'])
         {?><tr><td>Терминал:</td><td><? echo $this->rec_kz['terminal_name'].' ['.$this->rec_kz['terminal_id'].']' ;?></td></tr>
            <tr><td>Статус проверки:</td><td>
                     <? echo '<div class=mo_status_'.$this->rec_kz['status'].'>'.$this->rec_kz['_status_name'].'</div>' ;
                        if ($this->rec_kz['reason'])                      echo '<div class=red>'.$this->rec_kz['_reason'].'</div>' ;
                        if ($this->rec_kz['equipment'])                   echo '<div class=red>'.$this->rec_kz['_equipment'].'</div>' ;
                        if ($this->rec_kz['question_comment'])            echo '<div class=red>'.$this->rec_kz['question_comment'].'</div>' ;
                        if ($this->rec_kz['comment'])                     echo '<div class=red>'.$this->rec_kz['comment'].'</div>' ;
                     ?>
                 </td>
             </tr><?
          }
         if ($this->rec_kz['mo_id']){?><tr><td>МО:</td><td><? echo $this->rec_kz['mo_id']?></td></tr><?}
        ?></table>
      <div class="clear"></div>
      <?
  }
  function panel_quiz_view()
{       ?><h3>Результаты ответов</h3><?
        $session_questions=execSQL('select t1.*,
                                    t2.obj_name as question_name,t2.parent as question_section, 
                                    tres.answer_id,tres.correct as answer_correct 
                                    from quiz_sessions_questions t1
                                    left join  quiz_questions t2 on t2.pkey=t1.question_id
                                    left join  quiz_result tres on tres.quiz_id='.$this->rec_kz['pkey'].' and tres.question_id=t1.question_id
                                    where t1.parent='.$this->rec_kz['pkey'].' 
                                    order by t1.pkey') ;

        //$recs_answers=execSQL('select * from quiz_sessions_questions where parent='.$this->rec_kz['pkey'].' order by pkey desc',2) ;
        $recs_answers=execSQL('select * from quiz_result where quiz_id='.$this->rec_kz['pkey'].' order by pkey desc') ;
        $question_ids=array() ; $recs_contents=[] ;
        if (_sizeof($session_questions)) foreach($session_questions as $rec) $question_ids[]=$rec['question_id'] ;
        if (_sizeof($recs_answers)) foreach($recs_answers as $rec) $question_result_ids[$rec['question_id']]=$rec['correct'] ;
        if (_sizeof($question_ids)) $recs_answers=execSQL('select * from quiz_answers where question_id in ('.implode(',',($question_ids)).')') ;
        if (_sizeof($question_ids)) $recs_contents=execSQL('select * from quiz_content where question_id in ('.implode(',',($question_ids)).')') ;
        $recs_answers_by_question=group_by_field('question_id',$recs_answers) ;
        $recs_contents_by_question=group_by_field('question_id',$recs_contents) ;
        //damp_array($question_result_ids);
        ?><table class="basic fz_small full auto">
            <tr>
                <th>ID билета</th>
                <th>Тема</th>
                <th>Вопрос</th>
                <th>Фото/Видео контент</th>
                <th>Ответы</th>
                <th>Результат ответа</th>
            </tr><?
              if (_sizeof($session_questions)) foreach($session_questions as $rec)
              {   $rec_rasdel=QUIZ()->get_theme_by_id($rec['question_section']) ;
                  $arr=TREE('quiz_themes')->get_arr_parents_names($rec_rasdel['pkey'],array('from_level'=>2)) ;
                  $color_status=($rec['answer_correct'])? 'green':'red' ;
                  ?><tr>
                      <td><?echo $rec['question_id']?></td>
                      <td class="left"><?echo implode(' / ',$arr)?></td>
                      <td class="left"><?echo $rec['question_name']?></td>
                      <td><? if (_sizeof($recs_contents_by_question[$rec['question_id']])) foreach($recs_contents_by_question[$rec['question_id']] 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)
                            {   $class='' ;
                                if ($rec['answer_id']==$rec_answer['pkey']) $class=($rec['answer_correct'])? 'green bold':'red bold' ;
                                else if ($rec_answer['status']==1) $class='green' ;
                                ?><li class="<?echo $class?>"><?echo $rec_answer['obj_name']?></li><?
                            }
                            ?></ul></td>
                       <td><?
                            if (isset($question_result_ids[$rec['question_id']])) {?><span style="font-size:20px;color:<?echo $color_status?>"><?echo ($rec['answer_correct'])? 'Правильно':'Неправильно' ;?></span><?}
                            else echo '<div class=nowrap>Вопрос не задавался</div>' ;
                      ?></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 quiz_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><?
  }

}

?>
