<?php
class report_get_mo extends c_report
{
 var $title='Отчет по МО' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $show_on_page_peports=0 ;

 function setting($options=array())
 {   list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;
      // внимание! для не администратора тут только сам оператор
      ?><div id="panel_filter">
             <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                  <fieldset>
                      <div class="row">
                        <?
                        $this->filter_section_input_text('uid','UID сотрудника:',2) ;
                        $this->filter_section_input_text('name','Фамилия Имя Отчество:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                        $this->filter_section_input_text('propusk','Номер пропуска:',2) ;
                        $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                        $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                        $this->filter_section_input_text('mo_id','Id сессии МО:',2) ;
                        ?>
                        </div>
                        <div class="row">
                          <?
                          $this->filter_section_select('dopusk','Допуск:',2,$_SESSION['ARR_status_dopusk'],array('use_id_plus_1'=>0)) ;
                          $this->filter_section_select('tk','Тип контроля:',2,$_SESSION['ARR_mo_tk_type'],array('use_id_plus_1'=>1)) ;
                          $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                          $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                          ?>
                        </div>
                  </fieldset>
                  <?$this->panel_button_apply();?>
              </form>
       </div><br>
     <?
  }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;
     $usl=array() ;
     $usl[]=1 ;
     if ($this->filter['name'])              $usl[]='member_name like "'.$this->filter['name'].'%"' ;
     if ($this->filter['org_id'])            $usl[]='personal_parent2='.$this->filter['org_id'] ;
     if ($this->filter['org_ids'])           if (!is_array($this->filter['org_ids'])) $usl[]='personal_parent2 in ('.$this->filter['org_ids'].')' ;
     else                                    $usl[]='personal_parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if ($this->filter['otdel_id'])          $usl[]='personal_parent3='.$this->filter['otdel_id'] ;
     if ($this->filter['otdel_ids'])         if (!is_array($this->filter['otdel_ids'])) $usl[]='personal_parent3 in ('.$this->filter['otdel_ids'].')' ;
                                             else                                       $usl[]='personal_parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
     if ($this->filter['propusk'])           $usl[]='propusk="'.$this->filter['propusk'].'"' ;
     if ($this->filter['client_id'])        $usl[]='member_client_id='.$this->filter['client_id'] ;
     if ($this->filter['uid'])              $usl[]='member_uid="'.$this->filter['uid'].'"' ;
     if ($this->filter['tk'])              $usl[]='tk='.($this->filter['tk']-1).'' ;
     if ($this->filter['data_from'])        $usl[]='c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])          $usl[]='c_data<='.strtotime($this->filter['data_to']) ;
     if ($this->filter['mo_result'])            $usl[]='status='.$this->filter['mo_result'] ;
     if ($this->filter['dopusk'])            $usl[]='dopusk='.$this->filter['dopusk'] ;
     if ($this->filter['mo_type'])            $usl[]='mo_type='.$this->filter['mo_type'] ;
     if ($this->filter['mo_id'])            $usl[]='pkey='.$this->filter['mo_id'] ;


     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['client_id'])                       $info['клиент']=ACCOUNTS()->get_member_name_by_id($this->filter['client_id']) ;
   if ($this->filter['org_id'])                          $info['Организация']=PERSONAL()->get_org_names_by_ids($this->filter['org_id']) ;
   if ($this->filter['otdel_id'])                        $info['Подразделение']=PERSONAL()->get_org_names_by_ids($this->filter['otdel_id']) ;
   if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids($this->filter['org_ids']) ;
   if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids($this->filter['otdel_ids']) ;
   if ($this->filter['uid'])                             $info['UID сотрудника']='"'.$this->filter['uid'].'"' ;
   if ($this->filter['propusk'])                         $info['номер пропуска']='"'.$this->filter['propusk'].'"' ;
   if ($this->filter['mo_result'])                       $info['Результат МО']='"'.$_SESSION['ARR_status_sess'][$this->filter['mo_result']].'"' ;
   if ($this->filter['dopusk'])                          $info['Допуск']='"'.$_SESSION['ARR_status_dopusk'][$this->filter['dopusk']].'"' ;
   if ($this->filter['mo_type'])                         $info['Тип МО']='"'.$_SESSION['ARR_mo_type'][$this->filter['mo_type']].'"' ;
     if ($this->filter['tk'])                            $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;
     if ($this->filter['data_from'])                     $info['дата от']='"'.$this->filter['data_from'].'"' ;
     if ($this->filter['data_to'])                       $info['дата до']='"'.$this->filter['data_to'].'"' ;
   if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
   return $title ;
 }

  function get_cnt_items($usl,$options=array())
  { $cnt=execSQL_value('select count(pkey)
                        from  '.ESMO()->view_mo_session.'
                        where '.$usl,$options) ;
    return($cnt) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    $order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by pkey desc' ;
    //echo $usl ;
 	$list_rec=execSQL('select *
                       from  '.ESMO()->view_mo_session.'
                       where '.$usl.$order.$limit,$options) ;
    if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) ESMO()->prepare_public_info_to_mo($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    ?><table class="list_personal_table_img basic fz_small full auto"<?echo $id?>>
        <colgroup><col id="c1"><col id="c2"><col id="c3"><col id="c4"></colgroup>
        <tr><th>Пропуск</th><th>Фото</th><th>ФИО</th><th>Дата рождения</th><th>Возраст</th><th>Организация</th><th>Подразделение</th><th>Должность</th></tr><? ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        { ?><tr class=item>
                <td class="id"><?echo $rec['propusk']?><?if ($rec['demo_access']){?><div class="demo_access" title="Сотрудник может проходить неограниченное число МО"></div><?}?></td>
                <td class="img"><a  href="<?echo $rec['__href']?>" class="new_window" target="_blank" title="win_second"><img src="<?echo img_clone($rec,'small')?>"></a></td>
                <td class="left"><a href="<?echo $rec['__href']?>" class="new_window" target="_blank" title="win_second"><?echo $rec['obj_name']?></a>
                    <br><?echo '<span class="nowrap small">'.$rec['uid'].'</span>'?>
                    <?if (!$rec['enabled'])echo '<br><br><span class="red bold">УВОЛЕН</span> ('.date('d.m.Y H:i',$rec['fired_data']).')'?>

                </td>
                <td class="dr"><?echo $rec['dr']?></td>
                <td class="age"><?echo $rec['age']?></td>
                <td class="left"><?echo $rec['_org_name']?></td>
                <td class="left"><?echo $rec['_otdel_name']?></td>
                <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']?></td>
            </tr><?
        }
      ?></table><?
      //damp_array($rec) ;
  }

    function print_template_XML($list_recs,$options=array())
       { //damp_array($list_recs) ;
         //print_r($list_recs) ; trace() ;
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
         {   $item=add_element($this->xml_doc,$this->xml,'item','',array('id'=>$rec['pkey'])) ;
             add_element($this->xml_doc,$item,'fio',$rec['member_name']) ;
             add_element($this->xml_doc,$item,'dr',$rec['member_dr']) ;
             add_element($this->xml_doc,$item,'time_MO',$rec['_data']) ;
             add_element($this->xml_doc,$item,'time_dopusk_end',$rec['_data_dopusk_end']) ;
             add_element($this->xml_doc,$item,'mo_id',$rec['pkey']) ;
             add_element($this->xml_doc,$item,'doctor_comment',$rec['doctor_comment']) ;
             add_element($this->xml_doc,$item,'mo_result_id',$rec['status']) ;
             add_element($this->xml_doc,$item,'mo_result_text',$rec['_status_name']) ;
             add_element($this->xml_doc,$item,'mo_dopusk_id',$rec['dopusk']) ;
             add_element($this->xml_doc,$item,'mo_dopusk_text',$rec['_dopusk_name_full']) ;
             add_element($this->xml_doc,$item,'time_now',date('d.m.Y H:i:s')) ;
             add_element($this->xml_doc,$item,'terminal_name',$rec['terminal_name']) ;
             add_element($this->xml_doc,$item,'question',$rec['_question']) ;
             add_element($this->xml_doc,$item,'alko',$rec['_alko']) ;
             add_element($this->xml_doc,$item,'systolic',$rec['_systolic']) ;
             add_element($this->xml_doc,$item,'diastolic',$rec['_diastolic']) ;
             add_element($this->xml_doc,$item,'pulse',$rec['_pulse']) ;
             add_element($this->xml_doc,$item,'temperature',$rec['temperature']) ;
             add_element($this->xml_doc,$item,'tk',$rec['tk']+1) ;
         }
       }

       function print_template_JSON($list_recs,$options=array())
          { $result=array() ;
            if (_sizeof($list_recs)) foreach($list_recs as $rec)
              $result[]=array('fio'=>$rec['member_name'],
                              'uid'=>$rec['member_uid'],
                              'dr'=>$rec['member_dr'],
                              'time_MO'=>$rec['_data'],
                              'time_dopusk_end'=>$rec['_data_dopusk_end'],
                              'mo_id'=>$rec['pkey'],
                              'doctor_comment'=>$rec['doctor_comment'],
                              'mo_result_id'=>$rec['status'],
                              'mo_result_text'=>$rec['_status_name'],
                              'mo_dopusk_id'=>$rec['dopusk'],
                              'mo_dopusk_text'=>$rec['_dopusk_name_full'],
                              'time_now'=>date('d.m.Y H:i:s'),
                              'terminal_name'=>$rec['terminal_name'],
                              'question'=>$rec['_question'],
                              'alko'=>$rec['_alko'],
                              'systolic'=>$rec['_systolic'],
                              'diastolic'=>$rec['_diastolic'],
                              'pulse'=>$rec['_pulse'],
                              'temperature'=>$rec['temperature'],
                              'tk'=>$rec['tk']+1,
                             ) ;
              $text_json_out=json_encode($result) ;
              // возвращает ответ устройству
              echo $text_json_out ;

          }

    function manual_tags_in()
    {
        ?><table class="basic fz_normal left">
                    <tr><td>uid</td><td>Уникальный идентификатор сотрудника</td></tr>
                    <tr><td>name</td><td>ФИО сотрудника</td></tr>
                    <tr><td>propusk</td><td>пропуск</td></tr>
                    <tr><td>org_ids</td><td>ID организации, несколько организаций указывается через запятую</td></tr>
                    <tr><td>otdel_ids</td><td>ID подразделения, несколько подразделений указываются через запятую</td></tr>
                    <tr><td>dopusk</td><td>Результат допуска, 1 - разрешен, 2 - запрещен, 3 - уклонился</td></tr>
                    <tr><td>tk</td><td>Тип контроля, 1 - предсменный, 2 - послесменный, 3 - межсменный</td></tr>
                    <tr><td>data_from</td><td>Дата, время от, формат 01.03.2018 00:00</td></tr>
                    <tr><td>data_to</td><td>Дата, время до, формат 01.03.2018 00:00</td></tr>
                    <tr><td>mo_id</td><td>Id сессии МО</td></tr>
        </table><?
    }

    function manual_tags_out()
    {   ?><table class="basic fz_normal left">
                    <tr><td>time_now</td><td>текущее время сервера</td></tr>
                    <tr><td>fio</td><td>ФИО сотрудника</td></tr>
                    <tr><td>dr</td><td>дата рождения сотрудника</td></tr>
                    <tr><td>time_MO</td><td>дата/время прохождения МО</td></tr>
                    <tr><td>time_dopusk_end</td><td>срок действия допуска</td></tr>
                    <tr><td>mo_id</td><td>id сессии МО</td></tr>
                    <tr><td>doctor_comment</td><td>комментарий врача</td></tr>
                    <tr><td>mo_result_id</td><td>id результата МО на терминале (1: осмотр окончен, успешно, 2: осмотр окончен, ошибка, 3: осмотр не проводился)</td></tr>
                    <tr><td>mo_result_text</td><td>текстовое описание результата МО</td></tr>
                    <tr><td>mo_dopusk_id</td><td>id допуска(1: допуск получен, 2: допуск запрещен)</td></tr>
                    <tr><td>mo_dopusk_text</td><td>текстовое описание допуска</td></tr>
                    <tr><td>terminal_name</td><td>терминал, на котором сотрудник проходил МО</td></tr>
                    <tr><td>question</td><td>жалобы на состояние здоровья</td></tr>
                    <tr><td>alko</td><td>алкоголь</td></tr>
                    <tr><td>systolic</td><td>систолическое давление</td></tr>
                    <tr><td>diastolic</td><td>диалистическое давление<td></tr>
                    <tr><td>pulse</td><td>пульс</td></tr>
                    <tr><td>temperature</td><td>температура</td></tr>
                    <tr><td>tk</td><td>Тип контроля, 1 - предсменный, 2 - послесменный, 3 - межсменный</td></tr>
          </table>
        <?
    }




}

?>
