<?php
include_once(_DIR_EXT.'/events_docs/i_event_docs.php') ;
// специальный отчет для добавления сотрудников в группы
class report_personals_of_group extends c_report
{
 var $title='Группы сотрудников, направления по АГ' ;
 var $view_by_space_filter=0 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $allow_export_to_csv=1 ;

 function setting($options=array())
 {   if (!is_array($options['disabled_filter'])) $options['disabled_filter']=array() ;

     $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_mess_status=EVENT_DOCS()->arr_status ;
     //$arr_mess_status[99]='Не выдавалось' ;
     //$arr_mess_status[100]='Отсутствует скан' ;

     ?><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_select('atp_id','Место выдачи направления (АТП):',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) ;
                          $this->filter_section_input_text('name','ФИО, пропуск или UID:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                       ?></div><div class="row"><?
                          $this->filter_section_select_multiple('group_medic','Группа по болезни:',2,_IL('IL_group_medic')->recs) ;
                          $this->filter_section_select('doc_status','Статус направления:',2,$arr_mess_status) ;
                          $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                          $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                          ?>
                  </fieldset>
                  <?$this->panel_buttons();?>
              </form>
       </div><br>
     <?
  }


  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;
     $this->event_id=execSQL_value('select pkey from obj_site_events_schedule where clss=222 and type=2 and ext="events_docs/i_event_docs" and doc_code="napravlenie"') ;
     if (!$this->event_id) echo 'Не создано мероприятие по приему направлений АГ<br>' ;
     $usl=array() ;
     $usl[]='clss=211' ;
     $usl[]='enabled=1' ;
     $usl[]='pkey in (select personal_id from view_event_personals_docs where event_id='.$this->event_id.')' ;
     if ($this->filter['name'])              $usl[]='(obj_name like "'.$this->filter['name'].'%" or propusk="'.$this->filter['name'].'" or uid="'.$this->filter['name'].'")' ;
     if ($this->filter['org_ids'])          $usl[]='parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if ($this->filter['otdel_ids'])        $usl[]='parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
     if ($this->filter['atp_id'])            $usl[]='event_group_id='.$this->filter['atp_id'] ;
     //if ($this->filter['doc_status']==99)    $usl[]='t2.pkey is null and t3.pkey is null' ;
     //elseif ($this->filter['doc_status']==100)$usl[]='t3.pkey is null' ;
     //else
         if ($this->filter['doc_status'])   $usl[]='event_status='.$this->filter['doc_status'] ;
     if ($this->filter['data_from'])         $usl[]='event_pass_c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])           $usl[]='event_pass_c_data<='.strtotime($this->filter['data_to']) ;

     if (_sizeof($this->filter['group_medic']))  $usl['group_medic']=$this->get_usl_group_medic('pkey',$this->filter['group_medic']) ;


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

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if ($this->filter['name'])                  $info['ФИО, пропуск, UID']='"'.$this->filter['name'].'"' ;
   if ($this->filter['org_ids'])               $info['Организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_ids'])             $info['Подразделениe']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
   if ($this->filter['group_medic'])
   {   $arr=array() ;
       if (_sizeof(_IL('IL_group_medic')->recs)) foreach(_IL('IL_group_medic')->recs as $rec_group) if (isset($this->filter['group_medic'][$rec_group['pkey']])) $arr[]=$rec_group['obj_name'] ;
       if (_sizeof($arr)) $info['Группы']=implode(', ',$arr) ;
   }
   if ($this->filter['doc_status']==99)        $info['Статус направления']='Не выдавалось';
   elseif ($this->filter['doc_status']==100)   $info['Статус направления']='Отсутствует скан';
   else if ($this->filter['doc_status'])       $info['Статус направления']=EVENT_DOCS()->arr_status[$this->filter['doc_status']];
   if ($this->filter['propusk'])               $info['номер пропуска']='"'.$this->filter['propusk'].'"' ;
   if ($this->filter['atp_id'])                $info['Место выдачи']='"'.ACCOUNTS()->get_group_name($this->filter['atp_id']).'"' ;
   if ($this->filter['data_from'])                       $info['c']=$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())
  { //$options['debug']=1 ;
    $cnt=execSQL_value('select count(pkey)
                        from  view_event_personals_docs  
                        where '.$usl,$options) ;
    return($cnt) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    //if (_IS_SYSTEM_IP)
      // $options['debug']=2 ;
    $order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by event_pass_c_data desc' ; //' order by mess_c_data' ;
    // запрос по сотрудникам, состоящим в группе на выданные направления по АГ
    $list_recs=execSQL('select *
                       from  view_event_personals_docs
                       where '.$usl.$order.$limit,array('debug'=>$options['debug'],'no_indx'=>1)) ;

    if (_sizeof($list_recs)) foreach($list_recs as $i=>$rec) PERSONAL()->prepare_public_info_to_personal($list_recs[$i]) ;
    return($list_recs) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    $arr_personal_ids=array() ;
    $arr_atp_names=execSQL_row('select pkey,obj_name from obj_site_account where clss=206') ;
    //print_2x_arr($list_recs) ;
    ?><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><th>Должность</th><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)
        {   //$block_data=($rec['mess_block_from'])? $rec['mess_block_from']:$rec['mess_max_data'] ;
            $block_data=$rec['mess_block_from'];
            $group_id=($rec['event_group_id'])? $rec['event_group_id']:$rec['mess_group_id'] ;
            ?><tr class=item>
                <td><?if (!in_array($rec['pkey'],$arr_personal_ids)){?><input type="checkbox" name="_check[]" value="<?echo $rec['_reffer']?>"><?} else echo '<span class="red">Сотрудник уже в группе</span>'?></td>
                <td class="id"><?echo $rec['propusk']?></td>
                <td class="img"><a  href="/window/personal/person/<?echo $rec['pkey']?>/" class="new_window" target="_blank" title="win_second"><img src="<?echo img_clone($rec,'small')?>"></a></td>
                <td class="left"><a href="/window/personal/person/<?echo $rec['pkey']?>/" 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>
                <td class="left"><?echo (_sizeof($rec['_groups']))? implode(', ',$rec['_groups']):'-'?></td>
                <td><?if ($rec['event_status']) echo EVENT_DOCS()->arr_status[$rec['event_status']]?></td>
                <td><?if ($group_id) echo $arr_atp_names[$group_id]?></td>
                <td><?if ($rec['event_pass_c_data']) echo date('d.m.Y H:i',$rec['event_pass_c_data'])?></td>
                <td><?if ($block_data) echo date('d.m.Y H:i',$block_data) ; ?></td>
                <td><?if ($rec['event_status'] and $rec['event_status']==5) echo '<div class="green">Направление сдано '.date('d.m.Y',$rec['mess_close_data']).'</div>' ;
                        else  if ($block_data)
                        {
                            if ($block_data>time()) echo '<span class=cnt>'.floor(($block_data-time())/(60*60*24)).'</span>' ; else echo '<div class=red>Срок возврата направления истек</div>' ;
                        }
                ?>
                </td>
                <td><?if ($rec['event_status']<5 and $block_data<time()/* and $rec['mess_block_mo']==1*/) echo  '<div class="mo_alert">Прохождение МО заблокировано</div>'?></td>
                <td><?if ($rec['scan_id'])
                                    {   echo '№ '.$rec['scan_id'].'<br>' ;
                                        echo 'Статус <strong>'.$_SESSION['ARR_status_scan'][$rec['scan_status']].'</strong><br>' ;
                                        ?><button class="v2" cmd=esmo_magnit/open_scan scan_id="<?echo $rec['scan_id']?>">Открыть скан</button><?
                      }
                    ?>
                </td>
            </tr><?
        }
      ?></table><?
  }

    function print_template_CSV($list_recs,$options=array())
    { $i=$options['from'] ;
       $arr_atp_names=execSQL_row('select pkey,obj_name from obj_site_account where clss=206') ;
       if (_sizeof($list_recs)) foreach($list_recs as $rec)
       {
           //$block_data=($rec['mess_block_from'])? $rec['mess_block_from']:$rec['mess_max_data'] ;
           $block_data=$rec['mess_block_from'] ;
           $group_id=($rec['event_group_id'])? $rec['event_group_id']:$rec['mess_group_id'] ;

           $data=array() ;
      	   $data['№']=$i+1 ;
           $data['Пропуск']=$rec['propusk']  ;
           //$data['Табельный номер']=$rec['tabnumber']  ;
      	   $data['ФИО']=$rec['obj_name']  ;
           $data['UID']=$rec['uid']  ;
           $data['Дата рождения']=$rec['dr']  ;
           $data['Возраст']=$rec['age']  ;
      	   $data['Организация']=$rec['_org_name'] ;
      	   $data['Подразделение']=$rec['_otdel_name'] ;
           $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name'] ;
           $data['Группа']=(_sizeof($rec['_groups']))? implode(', ',$rec['_groups']):'-' ;
           $data['Статус направления']=EVENT_DOCS()->arr_status[$rec['event_status']] ;
           $data['Место выдачи']=$arr_atp_names[$rec['mess_atp_id']] ;
           $data['Дата выдачи']=($rec['event_pass_c_data'])? date('d.m.Y H:i',$rec['event_pass_c_data']):'' ;
           $data['Дата блокировки']=($block_data)? date('d.m.Y H:i',$block_data):'' ;
           $data['Дней до блокировки']=($rec['event_status']!=5 and $block_data)? (($block_data>time())? floor(($block_data-time())/(60*60*24)):''):'';
           $data['Дата сдачи']=($rec['event_status']==5 and $rec['mess_close_data'])? date('d.m.Y',$rec['mess_close_data']):'' ;
           $data['Блокировка МО']=($rec['event_status']!=5 and $rec['mess_close_data'] and $block_data<time()/* and $rec['mess_block_mo']==1*/)? 'Да':'' ;
           // вносим данные в csv
           $this->put_data_to_CSV($data,$i) ;
      	   $i++ ;
  	   }


   }



}

?>
