<?php
// специальный отчет для добавления сотрудников в группы
class report_personals_in_event extends c_report
{
 var $title='Участники мероприятия' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $rec_event=array() ;
 var $obj_event=null ;
 var $event_group_id=0 ;
 var $event_id=0 ;
 var $personal_id=0 ;
 var $group_id=0 ;
 var $status=array() ;
 var $pass_status=array() ;
 var $arr_pass_status=array() ;
 var $arr_temp_fired=array(0=>'Без сотрудников в отложенном увольнении',1=>'Все сотрудники') ;
 var $allow_export_to_csv=1 ;
 //var $report_script=_DIR_EXT.'/esmo_magnit_instruction/report_personals_in_event_instruction.php' ;
 var $filter_set=['name','org_ids','otdel_ids','working_ids','group_pers','group_medic','age_from','age_to','age_to','temp_fired','pass_status'];

 var $event_reffer ;
 var $personals_filter_reffer ;

 function init($options=array())
 {
    if ($this->event_id)
    { $this->rec_event=EVENTS()->get_event_by_id($this->event_id) ;
      $this->obj_event=EVENTS()->get_event_obj_by_id($this->event_id) ;
      $this->arr_pass_status=$this->obj_event->arr_status ;
      $this->event_reffer=$this->rec_event['_reffer'] ;
      $this->personals_filter_reffer=$this->rec_event['_reffer'];

      unset($this->arr_pass_status[0]) ;
    }
    //damp_array($this->rec_event);

 }

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

     list($arr_orgs_ids,$arr_otdel_ids,$arr_workd_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter,['filter_reffer'=>$this->rec_event['_reffer']]) ;
     $filter_set=array_flip($this->filter_set) ;


     $this->form->form_open() ;
     $this->form->hidden_var('filter[event_id]',$this->filter['event_id']) ;
     $this->form->row_open();
     if (isset($filter_set['name'])) $this->form->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
     if (isset($filter_set['org_ids'])) $this->form->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
     if (isset($filter_set['otdel_ids'])) $this->form->filter_section_select_multiple('otdel_ids','Подразделение:',3,$arr_otdel_ids) ;
     if (isset($filter_set['working_ids'])) $this->form->filter_section_select_multiple('working_ids','Должность:',3,$arr_workd_ids) ;
     if (isset($filter_set['pass_status'])) if ($this->obj_event!==null and !_sizeof($this->status)) $this->form->filter_section_select_multiple('status_ids','Статус в мероприятии:',2,$this->arr_pass_status) ;
     $this->form->row_close_open();
     if (isset($filter_set['group_pers'])) $this->form->filter_section_select_multiple('group_pers','Группа сотрудников:',2,_IL('IL_groups')->recs) ;
     if (isset($filter_set['group_medic'])) $this->form->filter_section_select_multiple('group_medic','Группа по болезни:',3,_IL('IL_group_medic')->recs) ;
     if (isset($filter_set['age_from'])) $this->form->filter_section_input_text('age_from','Возраст, от:',2) ;
     if (isset($filter_set['age_to'])) $this->form->filter_section_input_text('age_to','Возраст, до:',2) ;
     if (isset($filter_set['temp_fired'])) $this->form->filter_section_select('temp_fired','Отложенное увольнение:',2,$this->arr_temp_fired,array('nospace_element'=>1)) ;

     $this->form->row_close();
     $this->panel_buttons();
     $this->form->form_close() ;
  }


  function create_usl_select_obj($_params=array(),&$options=array())
  {  if ($options['debug']){?><strong>FILTER</strong><br><? damp_array($this->filter,1,-1) ;}
     $usl=array() ;
     $usl[]='t1.enabled=1';
     if ($this->event_id)                        $usl[]='t1.event_id='.$this->event_id ;
     if ($this->personal_id)                     $usl[]='t1.personal_id='.$this->personal_id ;

     if (_sizeof($this->status))                 $usl[]='t1.status in ('.implode(',',$this->status).')' ;
     if (_sizeof($this->pass_status))            $usl[]='t1.status in ('.implode(',',$this->pass_status).')' ;
     if (_sizeof($this->filter['status_ids']))   $usl[]='t1.status in ('.implode(',',array_keys($this->filter['status_ids'])).')' ;

     if (!$this->filter['temp_fired']) $this->filter['without_temp_fired']=1 ; // по умолчанию показываем сотрудников без отложенного увольнения

     // условия для сотрудников по ФЛ и СО набираются одинаково для всех отчетов, где есть выбор по сотрудникам
     PERSONAL()->get_usl_select_FL($this->filter,$usl,$this->left_join) ; // стандартные условия для отбора ФЛ + отбор по фильру аккаунта
     PERSONAL()->get_usl_select_SO($this->filter,$usl,$this->left_join) ; // стандартные условия для отбора СО

      //damp_array($options);
     if ($options['debug'])
     {
         ?><strong>main table usl</strong><br><?  damp_array($usl,1,-1) ;
         if (_sizeof($this->left_join)) {?><strong>LEFT JOIN</strong><br><? damp_array($this->left_join,1,-1);}
         if (_sizeof($this->unions))    {?><strong>UNIONS</strong><br><? damp_array($this->unions,1,-1);}
     }

     $this->prepare_SQL_left_join() ;

     $usl_res=(_sizeof($usl))? implode(' and ',$usl):'1' ;
     return($usl_res) ;
  }

  function get_arr_info_filters()
  { $info=parent::get_arr_info_filters() ;

    if ($this->filter['status'])       $info['Статус']=$this->obj_event->get_status_by_ids($this->filter['status']) ;
    if (_sizeof($this->filter['status_ids'])) $info['Статус']=$this->obj_event->get_status_by_ids($this->filter['status_ids'],array('ids_in_keys'=>1)) ;
    if (isset($this->filter['temp_fired']) and !$this->filter['temp_fired'])  $info['Отбор сотрудников']='Без отложенного увольнения';
    if (MEMBER()->setting['personal']['usl_select'] and MEMBER()->setting['personal']['info_filter'])  $info[MEMBER()->setting['personal']['name']]=strip_tags(MEMBER()->setting['personal']['info_filter']);
    return $info ;
  }

  // внимаение! при всем желании невозможно вместо left join использовать отдельные запросы по условиям к ФЛ и СО, так как понятие группы
  // подразумевает совокупность фильтров по ФЛ и СО, например "ООО парнас + возраст 22-28", и эти условия должны идти через AND
  // что не реализовать, если разнести эти условия по таблицам запроса fl и so

 function get_cnt_items($usl,$options=array())
  {  $options['debug']=$this->debug ;

    $cnt=execSQL_value('select count(distinct(fl.pkey))
                        from  obj_site_events_pass t1
                        left join obj_site_personals fl on fl.pkey=t1.personal_id
                        left join obj_site_workers so on so.personal_id=t1.personal_id
                        '.$this->join_table.'
                        where '.$usl.$this->join_usl.
                        ' and not fl.pkey is null and not so.pkey is null ',$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 obj_name' ;
    //$options['debug']=2 ;
    //if (!isset($options['no_indx'])) $options['no_indx']=1 ;
    $list_rec=execSQL('select fl.*,
                        t1.pkey as event_person_id,
                        t1.pkey as event_pass_id,
                        t1.tkey as event_person_tkey,
                        t1.tkey as event_pass_tkey,     
                        t1.group_id as event_group_id,
                        t1.event_id,
                        t1.personal_id,
                        t1.mess_id,
                        t1.result,
                        t1.fname as event_doc_fname,
                        t1.status as event_status,
                        t1.status as pass_status,
                        t1.status as event_pass_status,
                        t1.time_print as time_print,
                        t1.c_data as event_c_data,
                        t1.data_from as data_from,
                        t1.data_to as data_to
                       from obj_site_events_pass t1
                       left join view_personals fl on fl.pkey=t1.personal_id
                       left join obj_site_workers so on so.personal_id=t1.personal_id
                       '.$this->join_table.'
                       where '.$usl.'
                       '.$this->join_usl.' and  not fl.pkey is null and  not so.pkey is null  
                       group by fl.pkey
                       '.$order.$limit,$options) ;

 	PERSONAL()->full_personals_SO_info($list_rec) ; // заполняем информацию по СО в записи по ФЛ
    PERSONAL()->full_personals_medic_groups($list_rec) ; // заполняем информацию по медгруппам в записи по ФЛ
    PERSONAL()->full_org_othdels_work_names($list_rec) ; // заполняем информацию по медгруппам в записи по ФЛ

    if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) PERSONAL()->prepare_public_info_to_personal_v2($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    //print_2x_arr($list_recs);
    $arr_PID=array() ;  $arr_SP=array() ;  $cnt_mess_pers=array() ; $cnt_mess=array() ; $tkey=0 ;
    if (_sizeof($list_recs)) foreach($list_recs as $rec) {$arr_PID[]=$rec['pkey'] ; $arr_SP[]=$rec['event_pass_id'] ; $tkey=$rec['event_pass_tkey'] ; }
    if (_sizeof($list_recs)) $cnt_mess=execSQL('select personal_id,status,count(pkey) as cnt from obj_site_personal_mess where source_pkey in ('.implode(',',$arr_SP).') and source_tkey='.$tkey.' and personal_id in ('.implode(',',$arr_PID).') group by personal_id,status',0,1) ;
    if (_sizeof($cnt_mess)) foreach($cnt_mess as $rec) $cnt_mess_pers[$rec['personal_id']][$rec['status']]=$rec['cnt'] ;
    $arr_personal_ids=array() ;
    ?><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>ID</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><a href="/cab/events/pass/<?echo $rec['event_pass_id']?>/" class="new_window" target="_blank" title="win_pass_info"><?echo $rec['event_pass_id']?></a></td>
                <td><?echo date('d.m.Y H:i',$rec['event_c_data'])?></td>
                <td class="left"><a href="<?echo $rec['__href_window']?>" class="new_window" target="_blank" title="win_second"><?echo $rec['obj_name']?></a>
                    <?  if ($rec['uid']) echo '<br><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']).')' ;
                        if ($rec['dr'])echo '<br>'.$rec['dr'] ;
                        if ($rec['age'])echo ', '.$rec['age'].' '.get_case_by_count_1_2_5($rec['age'],'год,года,лет');
                        if ($rec['fired_data'])echo '<div style="color:burlywood;">Отложенное увольнение до <strong>'.date('d.m.Y',$rec['fired_data']).'</strong></div>' ;
                    ?>
                </td>
                <td class="left"><?echo '<strong>'.$rec['_org_name'].'</strong><br><div class="small">'.$rec['_otdel_name'].'</div>'?></td>
                <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name'] ;
                                  if ($rec['working2']) echo '<br><strong>Совмещение: </strong>'._IL('IL_works')->recs[$rec['working2']]['obj_name'] ;
                    ?></td>
                <td><?echo EVENT_INSTR()->arr_status[$rec['event_status']]?></td>
                <td><?  $arr=array() ;
                        if (_sizeof($cnt_mess_pers[$rec['pkey']])) foreach($cnt_mess_pers[$rec['pkey']] as $status=>$cnt) $arr[]=$_SESSION['ARR_mess_status'][$status].(($cnt)? ' '.$cnt.' шт.':'');
                        if (_sizeof($arr)) echo implode('<br>',$arr) ;
                        //print_r($cnt_mess_pers[$rec['pkey']]) ;
                    ?></td>
            </tr><?
        }
      ?></table><?
      //damp_array($rec) ;

      //echo 'Фильтр аккаунта по сотрудникам: ' ; damp_array(MEMBER());
  }

    function print_template_CSV($list_recs,$options=array())
       {  $i=$options['from'] ;
          include_once(_DIR_EXT.'/esmo_magnit_instruction/i_event_instruction.php') ;
           $arr_PID=array() ;  $arr_SP=array() ;  $cnt_mess_pers=array() ; $cnt_mess=array() ;
           if (_sizeof($list_recs)) foreach($list_recs as $rec) {$arr_PID[]=$rec['pkey'] ; $arr_SP[]=$rec['event_pass_id'] ; }
           if (_sizeof($list_recs)) $cnt_mess=execSQL('select personal_id,status,count(pkey) as cnt from obj_site_personal_mess where source_pkey in ('.implode(',',$arr_SP).') and personal_id in ('.implode(',',$arr_PID).') group by personal_id,status',0,1) ;
           if (_sizeof($cnt_mess)) foreach($cnt_mess as $rec) $cnt_mess_pers[$rec['personal_id']][$rec['status']]=$rec['cnt'] ;



         if (_sizeof($list_recs)) foreach($list_recs as $rec)
           { $data=array() ;
             $data['ID']=$rec['pkey'] ;
             $data['Дата добавления в инструктаж']= date('d.m.Y H:i',$rec['event_c_data']) ;
             $data['ФИО сотрудника']=$rec['obj_name'] ;
             $data['ДатаРожд']=$rec['dr'] ;
             $data['Возраст']=$rec['age'] ;
             $data['Организация']=$rec['_org_name'] ;
             $data['Подразделение']=strip_tags($rec['_otdel_name']) ;
             $data['Основная должность']=_IL('IL_works')->recs[$rec['working']]['obj_name'];
             $data['Совмещение']=($rec['working2'])? _IL('IL_works')->recs[$rec['working2']]['obj_name']:'' ;
             $data['GUID']=$rec['uid'] ;
             $data['Пропуск']=$rec['propusk'] ;
             $data['Статус']= EVENT_INSTR()->arr_status[$rec['event_status']] ;

             $arr=array() ;
             if (_sizeof($cnt_mess_pers[$rec['pkey']])) foreach($cnt_mess_pers[$rec['pkey']] as $status=>$cnt) $arr[]=$_SESSION['ARR_mess_status'][$status].(($cnt>1)? ' '.$cnt.' шт.':'');
               $data['Сообщения']=(_sizeof($arr))? implode(', ',$arr):'' ;


             $this->put_data_to_CSV($data,$i) ;
             $i++ ;
           }

       }



}

?>
