<?
// вниамение!!!
// во всех фильтрах:
// data_from, data_to - дата в текстовом формате
// time_from, time_to - дата в UNIX формате

class report_quiz_sessions extends c_report
{
 var $title='Журнал сессий КЗ' ;
 var $mo_sort='pkey' ;
 public $view_by_space_filter=1 ;
 public $personal_id=0 ;
 public $event_id=0 ;
 public $session_ids=0 ;

 function init($options=array())
 {
    //if (!$this->filter['group_id']) $this->filter['group_id']=MEMBER()->cur_group_id ;
 }

 function setting()
 {
     $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
     list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;
     $arr_terminals=ESMO()->get_list_terminals(MEMBER()->cur_group_id) ;

     $this->form_open() ;
     $this->row_open() ;

    $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
    $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
    $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
    if (!$this->personal_id) $this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
    $this->filter_section_input_text('id_mo','ID КЗ:',2) ;
    $this->filter_section_select('terminal_id','Терминал:',2,$arr_terminals,array('key_fname'=>'id')) ;
    $this->row_close_open() ;
    $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
    $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
    $this->panel_button_apply();
    $this->form_close() ;
}

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;     //damp_array($this->filter,1,-1) ;
   if ($this->filter['data_from'])                       $info['c']=$this->filter['data_from'] ;
   if ($this->filter['data_to'])                         $info['по']=$this->filter['data_to'] ;
   if ($this->filter['time_from'])                       $info['c']=date('d.m.Y H:i',$this->filter['time_from']) ;
   if ($this->filter['time_to'])                         $info['по']=date('d.m.Y H:i',$this->filter['time_to']) ;
   if ($this->filter['group_id'])                        $info[$GLOBALS['LS_person_group_title'].':']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
   if ($this->filter['org_id'])                          $info['Организация']=PERSONAL()->get_name_by_id($this->filter['org_id'])  ;
   if ($this->filter['otdel_id'])                        $info['Подразделение']=PERSONAL()->get_name_by_id($this->filter['otdel_id'])  ;
   if ($this->filter['org_ids'])                         $info['Организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_ids'])                       $info['Подразделение']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
   if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
   if ($this->filter['tk'])                              $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;

   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['propusk'])                         $info['Пропуск']='"'.$this->filter['propusk'].'"' ;
   if ($this->filter['id_mo'])                           $info['ID КЗ']='"'.$this->filter['id_mo'].'"' ;
   if ($this->filter['doctor_id'])                       $info['Фельдшер']=ACCOUNTS()->get_member_name_by_id($this->filter['doctor_id'])  ;
   if ($this->filter['terminal_id'])                     $info['Терминал']=$this->filter['terminal_id']  ;
   if ($this->filter['status'])                          $info['Осмотр на терминале']=$_SESSION['ARR_status_sess'][$this->filter['status']]  ;
   if ($this->filter['ef'])                              $info['Ошибка оборудования']='Да'  ;
   if ($this->filter['equipmentFailure'])                $info['Ошибка оборудования']='Да'  ;
   if ($this->filter['equipmentError'])                  $info['Ошибка измерения']='Да'  ;
   if ($this->filter['equipment'])                       $info['Устройство'][]=$this->filter['equipment']  ;

   if (MEMBER()->setting['personal']['usl_select'])     $info[MEMBER()->setting['personal']['name']]=strip_tags(MEMBER()->setting['personal']['info_filter']);


   if (_sizeof($info)) foreach($info as $title=>$value)   if (is_array($value)) $_str[]=$title.': <strong>'.implode(', ',$value).'</strong>' ; else $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
   return $title ;

 }

 function create_usl_select_obj($_params,&$options)
 { //damp_array($this->filter,1,-1);
   $_usl[]='t1.personal_id>0' ;
   $_usl[]='t1.status>1' ;
   if ($this->personal_id) $_usl[]='t1.personal_id='.$this->personal_id ;
   if ($this->event_id) $_usl[]='t1.event_id='.$this->event_id ;
   if (_sizeof($this->filter['org_ids']))    $_usl[]='t1._org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
   if (_sizeof($this->filter['otdel_ids']))  $_usl[]='t1._otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
   if ($this->filter['group_id']>1)           $_usl[]='t1.group_id='.$this->filter['group_id'].'' ;
   if ($this->filter['name'])               $_usl[]='t1.personal_name like "%'.$this->filter['name'].'%"' ;
   if ($this->filter['id_mo'])              $_usl[]='t1.pkey='.$this->filter['id_mo'].'' ;
   if ($this->filter['terminal_id'])        $_usl[]='t1.terminal_id='.$this->filter['terminal_id'].'' ;
   if ($this->filter['data_from'])          $_usl[]='t1.c_data>='.strtotime($this->filter['data_from']) ;
   if ($this->filter['data_to'])            $_usl[]='t1.c_data<='.strtotime($this->filter['data_to']) ;
   if ($this->session_ids)            $_usl[]='t1.pkey in ('.$this->session_ids.')' ;

   $_usl[]='not tp.pkey is null' ;

   //damp_array($_usl,1,-1);
   $usl_res=(_sizeof($_usl))? implode(' and ',$_usl):1 ;
   return($usl_res) ;
 }

  function get_cnt_items($usl,$options=array())
  { $options['debug']=0 ;
    $this->cnt_items=execSQL_value('select count(t1.pkey) 
                                    from view_quiz_session t1 
                                    left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                                    where '.$usl,$options) ;
    return($this->cnt_items) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    $order=' order by c_data desc' ;
    $options['debug']=0 ;
    $recs=execSQL('select t1.* 
                   from view_quiz_session t1
                   left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                   where '.$usl.$order.$limit,$options) ;
    if (_sizeof($recs) and !$options['no_public_info']) foreach($recs as $id=>$rec) QUIZ()->prepare_public_info_to_kz($recs[$id],$options) ;
    return($recs) ;
  }

 // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {  $options['id']='panel_last_mo' ;
     $options['base_dir']='' ;
     if (!isset($options['no_reverse_indx'])) $options['no_reverse_indx']=$this->filter['skoro'] ;
     $id=($options['id'])? 'id='.$options['id']:'' ;
     ?><div class="basic fz_small full" <?echo $id?>>
          <table class="basic fz_small full auto">
            <tr class="head"><th>№</th><th>Дата/время</th><th>Метод КЗ</th><th>ФИО<br>сотрудника</th><th>Фото</th><th>Мероприятие КЗ</th><th>Темы КЗ</th><th>Результат КЗ</th><th>Статус проверки</th></tr><?
            $i=($options['no_reverse_indx'])? 1:_sizeof($list_recs) ;
            if (_sizeof($list_recs)) $recs=execSQL('select t1.*,
                                                   t2.obj_name as question_name, 
                                                   t3.pkey as rasdel_id,t3.obj_name as rasdel_name, 
                                                   t4.pkey as theme_id,t4.obj_name as theme_name 
                                                   from quiz_result t1
                                                   left join quiz_questions t2 on t2.pkey=t1.question_id
                                                   left join quiz_themes t3 on t3.pkey=t2.parent
                                                   left join quiz_themes t4 on t4.pkey=t3.parent2
                                                   where t1.quiz_id in ('.implode(',',array_keys($list_recs)).') 
                                                   order by t1.pkey desc') ;
            $quiz_results=array() ;
            if (_sizeof($recs)) foreach($recs as $rec)
              { $quiz_results[$rec['quiz_id']]['cnt_questions']++ ;
                $quiz_results[$rec['quiz_id']]['cnt_correct']+=$rec['correct'] ;
                $quiz_results[$rec['quiz_id']]['themes'][]=(_sizeof($quiz_results[$rec['quiz_id']]['themes'])+1).'. '.$rec['theme_name'].' / '.$rec['rasdel_name'] ;
              }

            //damp_array($quiz_results);
            if (_sizeof($list_recs)) foreach($list_recs as $rec)
              {   $options['i']=$i ;
                  $quiz_result=$quiz_results[$rec['pkey']] ;
                      {   if (!$quiz_result['cnt_questions']) $td_class='' ;
                          else if ($quiz_result['cnt_questions']==$quiz_result['cnt_correct']) $td_class='bg_green' ;
                          else if ($quiz_result['cnt_correct']==0) $td_class='bg_red' ;
                          else if ($quiz_result['cnt_questions']!=$quiz_result['cnt_correct']) $td_class='bg_yellow' ;
                          else $td_class='' ;
                          ?><tr class=item id="mo_tr_<?echo $rec['pkey']?>">
                                    <td><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['pkey']?></a><?if ($rec['personal_demo_access']){?><div class="demo_access" title="Сотрудник может проходить неограниченное число МО"></div><?}?></td>
                                    <td><?echo $rec['_data']?><br><?echo $rec['_doctor_name']?></td>
                                    <td><?echo $rec['_reader']?>
                                        <?if ($rec['_term_cam_1'] or $rec['video'] or $rec['_use_in_trassir']){?>&nbsp;<span class="v2" cmd="media_server/get_video_from_terminal" id_mo="<?echo $rec['mo_id']?>"><i class="fa fa-video-camera black"></i></span><?}?>
                                    </td>
                                    <td class="name">
                                    <?  $arr_info=array() ;
                                        if ($rec['personal_id']) $arr_info[]='<a class="new_window" '.($rec['personal_danger_work']?'style="background-color:orange"':'').' target="_blank" title="win_second" href="/window/personal/person/'.$rec['personal_id'].'/">'.$rec['personal_name'].'</a>' ;
                                        if ($rec['_org_name']) $arr_info[]=$rec['_org_name'] ;
                                        if ($rec['_otdel_name']) $arr_info[]=$rec['_otdel_name'] ;
                                        //if (MEMBER()->rol==1 and $rec['propusk']) $arr_info[]='Пропуск: '.$rec['propusk'] ;
                                        if (_sizeof($arr_info)) echo implode('<br>',$arr_info) ;
                                    ?>
                                    </td>
                                    <td class="photo"><div>
                                        <div class="img"><? if ($rec['_personal_img']) { ?><img width=100 src="<?echo $rec['_personal_img']?>"><?}?></div>
                                        <?if ($rec['reader']!='email'){?><div class="img"><? if ($rec['_personal_img_auth']) {?><img width=100 src="<?echo $rec['_personal_img_auth']?>"><?}?></div><?}?>
                                        <div class="clear"></div></div>
                                    </td>
                                    <td><?echo $rec['event_name']?></td>
                                    <td class="left"><?if (_sizeof($quiz_result['themes'])) echo implode('<br>',$quiz_result['themes'])?></td>
                                    <td class="result v1 <?echo $td_class?>" href="<?echo $rec['__href']?>" window="window_quiz_session"><?if ($quiz_result['cnt_questions']){?><span class="result"><?echo $quiz_result['cnt_correct']?></span> ИЗ <span class="result"><?echo $quiz_result['cnt_questions']?></span><?}?></td>
                                    <td class="comment"><?  if ($rec['status']==2) echo '<div class=ok>'.$rec['_status_name'].'</div>' ;
                                                            echo $rec['_comment'];
                                                            $rec['terminal_comment']=str_replace($rec['comment'],'',$rec['terminal_comment']) ;  // убираем дублирующиемся надписи, пока временно, так
                                                            if ($rec['terminal_comment']) {?><div class="terminal_comment"><i class="fa fa-desktop" aria-hidden="true"></i> <?echo $rec['terminal_comment']?></div><?}
                                                            // тут идет лишний запрос к БД, в записи $rec уже присутствуют все значения, которые выбираются в функции get_result_sign_verification
                                                           // можно передавать сразу массив $rec: signature()->get_result_sign_verification($rec)
                                                           // а в функции просто анализировать переданные значения
                                                            //print_r($rec);
                                                           //$res_DTW=signature()->get_result_sign_verification($rec) ;
                                                           // если у человека есть подпись и МО пройден
                                                           if ($rec['sign_id'] > 0 and ($rec['status']==2 or $rec['status']==3))
                                                           { if ($rec['DTW_res']) echo '<div class="green">Подпись верна</div>';
                                                             else                 echo '<div class="red">Подпись неверна</div>' ;
                                                           }
                                                           //if (stripos('intrusion',$rec['reason'])!==false) echo '<div class="red">Требуется подтверждение личности</div>' ;
                                                        ?>
                                        <?if ($rec['__dlit_mo']) echo '<br>'.$rec['__dlit_mo'].' c' ;

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

                  if ($options['no_reverse_indx']) $i++ ; else $i-- ;
              }


          ?></table><div id="panel_image_preview"></div></div>
          <script type="text/javascript">
              $j(document).ready(function()
              {    $j('div.list_mo_sessions td.photo div.img img').hover(
                      function() { $j('div#panel_image_preview').addClass('active').html('<img src="'+$j(this).attr('src')+'">');},
                      function() {  $j('div#panel_image_preview').removeClass('active');}
                    ) ;
              }) ;
          </script>
          <style>
              span.result{font-size:20px;}
          </style>

          <?
    //  damp_array($quiz_results);
      }



}
?>
