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

class report_mo_tk extends c_report
{
 var $title='Отчет по предсменным / послесменным осмотрам' ;
// var $view_only_model=1 ;
 var $mo_sort='member_name' ;
 var $allow_export_to_csv=1 ;
 var $max_personal_parent_cnt=0;
 var $use_max_personal_parent=0;

 function setting()
{ if (isset($this->filter['time_from'])) $this->filter['data_from']=date('d.m.Y',$this->filter['time_from']);
  if (isset($this->filter['time_to'])) $this->filter['data_to']=date('d.m.Y',$this->filter['time_to']);
  $parent_lvl_array=execSQL_van('select max(parent4) as max_parent4,max(parent5) as max_parent5,max(parent6) as max_parent6,max(parent7) as max_parent7,max(parent8) as max_parent8,max(parent9) as max_parent9 from '.PERSONAL()->table_name.' where clss=211');
  if (_sizeof($parent_lvl_array)) {
      if ($parent_lvl_array['max_parent4']) $this->use_max_personal_parent=2;
      if ($parent_lvl_array['max_parent5']) $this->use_max_personal_parent=3;
      if ($parent_lvl_array['max_parent6']) $this->use_max_personal_parent=4;
      if ($parent_lvl_array['max_parent7']) $this->use_max_personal_parent=5;
      if ($parent_lvl_array['max_parent8']) $this->use_max_personal_parent=6;
      if ($parent_lvl_array['max_parent9']) $this->use_max_personal_parent=7;
  }
  $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) ;
  ?><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('name','ФИО:',3,array('auto_complete'=>"autocomplette_personal_name")) ;
                    $this->filter_section_select('group_id','Группа:',2,$arr_groups) ;
                    $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                    $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                    ?>
                </div>
                <div class="row">
                    <?
                    $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                    $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                    ?>
                </div>
                <?if ($this->use_max_personal_parent) {?>
                    <div class="row">
                        <section class="col col-3">
                            <label class="checkbox"><input type="checkbox" name="filter[view_department_lvl]" value="1"  <?if ($this->filter['view_department_lvl']=='1') echo 'checked'?>><i></i>Отображать вложенные подразделения</label>
                        </section>
                        <?
                        $department_lvl_array=[];
                        for ($i=2;$i<=$this->use_max_personal_parent;$i++) $department_lvl_array[$i]='Уровень '.$i;
                        $this->filter_section_select('department_lvl','Глубина вложенных подразделений:',2,$department_lvl_array,['nospace_element'=>1]) ;
                        ?>
                    </div>
                <?
                }
                ?>
            </fieldset>
            <?$this->panel_buttons();?>
        </form>
     </div>
  <?
}

function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   //if (MEMBER()->rol==2) $this->filter['group_id']=MEMBER()->cur_group_id ;
   if ($this->filter['data_from'])                       $info['c']=$this->filter['data_from'] ;
   if ($this->filter['data_to'])                         $info['по']=$this->filter['data_to'] ;
   if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
   if ($this->filter['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
   if ($this->filter['org_ids'])                          $info['организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_id'])                        $info['подразделение']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['group_id'])                        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
   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) ;
// if (MEMBER()->rol==2) $this->filter['group_id']=MEMBER()->cur_group_id ;
     $options_select=array() ;

   $options_select['status']='2,3' ;  // только завершенные МО

   $options_select['dopusk']='1,2,3' ;

   if ($this->filter['status'])    $options_select['status']=$this->filter['status'] ;
   if ($this->filter['status'])    $options_select['status']=$this->filter['status'] ;
   if ($this->filter['group_id'])  $options_select['group_id']=$this->filter['group_id'] ;
   if ($this->filter['time_from']) $options_select['time_from']=$this->filter['time_from'] ;
   if ($this->filter['data_from']) $options_select['data_from']=$this->filter['data_from'] ;
   if ($this->filter['time_to'])   $options_select['time_to']=$this->filter['time_to'] ;
   if ($this->filter['data_to'])   $options_select['data_to']=$this->filter['data_to'] ;
   if ($this->filter['dep_id'])    $options_select['dep_id']=$this->filter['dep_id'] ;
   if ($this->filter['org_id'])    $options_select['org_id']=$this->filter['org_id'] ;
   if ($this->filter['org_ids'])  $options_select['org_ids']=implode(',',array_keys($this->filter['org_ids'])) ;
   if ($this->filter['otdel_id'])  $options_select['otdel_id']=$this->filter['otdel_id'] ;
   if ($this->filter['name'])      $options_select['name']=$this->filter['name'] ;
   if ($this->filter['propusk'])   $options_select['propusk']=$this->filter['propusk'] ;

   if ($this->filter['view_department_lvl']) {
       if ($this->filter['department_lvl']>=2) {
           $this->max_personal_parent_cnt=$this->filter['department_lvl'];
       }
   }


   $options_select['use_member_personal_filter']=$options['dont_use_member_personal_filter']?0:1 ;

  // damp_array($this->filter,1,-1) ;
   //damp_array($options_select,1,-1) ;
   $options_select['debug']=0 ;
   $usl_res=ESMO()->get_usl_select_mo_by_filter($options_select) ;
   //if (_IS_SYSTEM_IP)
// echo $usl_res ;
   return($usl_res) ;
 }

  function get_cnt_items($usl,$options=array())
  { //$options['debug']=2 ;
      $recs=execSQL('select distinct(member_id) from '.ESMO()->view_mo_session.' where '.$usl,$options);
      $this->cnt_items=_sizeof($recs);
//    $this->cnt_items=execSQL_value('select count(pkey) from '.ESMO()->view_mo_session.' where '.$usl,$options) ;
    return($this->cnt_items) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    //$order=($options['order'])? ' order by '.$options['order']:' order by '.$this->mo_sort ;
    $order=' order by '.$this->mo_sort ;
//      $options['debug']=2 ;
      $recs=execSQL('select distinct(member_id),member_name,_org_name,_otdel_name,working,personal_parent1,personal_parent2,
                                  personal_parent3,personal_parent4,personal_parent5,personal_parent6,personal_parent7,personal_parent8,personal_parent9
                                  from '.ESMO()->view_mo_session.' where '.$usl.$order.$limit,$options) ;

    $member_ids=array_keys($recs);

    $mo_recs=execSQL('select pkey,c_data,tk,member_id from '.ESMO()->view_mo_session.' where '.$usl.' and member_id in('.implode(',',$member_ids).') order by pkey asc',$options['debug']);

    if (_sizeof($mo_recs)) foreach ($mo_recs as $mo_rec)
    {
        //увеличиваем счетчик типа МО
        if (!$mo_rec['tk']) {
            //тип МО предсменный
            $recs[$mo_rec['member_id']]['mo_before_cnt']++;
            //если предыдущий МО предсменный - пропущен послесменный
            if (isset($recs[$mo_rec['member_id']]['last_mo']['type']) and $recs[$mo_rec['member_id']]['last_mo']['type']==0)
            {
                $recs[$mo_rec['member_id']]['date_without_after_mo'].=date('d.m.Y',$recs[$mo_rec['member_id']]['last_mo']['date']+60*60*$GLOBALS['LS_setting_smena_after']).'<br>';
            }
        }
        else
        {
            $recs[$mo_rec['member_id']]['mo_after_cnt']++;
        }
        //запоминаем дату и тип последнего МО
        $recs[$mo_rec['member_id']]['last_mo']['type']=$mo_rec['tk'];
        $recs[$mo_rec['member_id']]['last_mo']['date']=$mo_rec['c_data'];
    }

    if ($this->filter['data_to']) $filter_date_to=strtotime($this->filter['data_to']);
    $now_time=time();

    //проверка последних МО каждого сотрудника
    if (_sizeof($recs)) foreach ($recs as $rec)
    {
        //если тип МО послесменный
        if (isset($rec['last_mo']) and $rec['last_mo']['type']==0)
        {
            if ($filter_date_to)
            {
                //если задан фильтр дата до
                if ($filter_date_to<$now_time) $date_for_compare=$filter_date_to; else $date_for_compare=$now_time;
                //сравниваем с датой до филтра или с текущим временем
                $this->check_date_for_skip_mo($recs[$rec['member_id']]['date_without_after_mo'],$rec['last_mo']['date'],$date_for_compare);
            }
            else
            {
                //сравниваем с текущим временем
                $this->check_date_for_skip_mo($recs[$rec['member_id']]['date_without_after_mo'],$rec['last_mo']['date'],$now_time);
            }
        }
    }
//    print_2x_arr($recs);
    return($recs) ;
  }

  function check_date_for_skip_mo(&$member_rec,$last_mo_date,$date_for_compare)
  {
    if (($date_for_compare-$last_mo_date)>(60*60*$GLOBALS['LS_setting_smena_after']))
        $member_rec.=date('d.m.Y',$last_mo_date+60*60*$GLOBALS['LS_setting_smena_after']).'<br>';
  }

 // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {
    ?>
      <table class="basic full fz_small" >
        <tr>
          <th >№</th>
          <th >ФИО<br>сотрудника</th>
          <th>Должность</th>
          <th>Организация</th>
          <th>Подразделение</th>
          <?
          if ($this->max_personal_parent_cnt>=2) {
              for($j=2;$j<=$this->max_personal_parent_cnt;$j++) {
                  echo '<th>Подразделение<br>(уровень '.$j.')</th>';
              }
          }
          ?>
          <th>Кол-во предсменных осмотров</th>
          <th>Кол-во послесменных осмотров</th>
          <th>Даты, в которые работник не прошел послесменный осмотр</th>
          </tr>
        <?
        $i=$this->first_obj ; ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {
            $personal_usl='';
            if ($this->filter['data_from'])  $personal_usl.=',data_from='.$this->filter['data_from'];
            if ($this->filter['data_to'])  $personal_usl.=',data_to='.$this->filter['data_to'];
            ?><tr class=item>
                <td><?echo '<a href="/cab/reports/report_mo3/[personal_id='.$rec['member_id'].$personal_usl.']/">'.$i.'</a>';  $i++ ;?></td>
                <td><?echo '<a href="/cab/personal/person/'.$rec['member_id'].'/">'.$rec['member_name'].'</a>'?></td>
                <td><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']?></td>
                <td><?echo $rec['_org_name']?></td>
                <td><?echo $rec['_otdel_name']?></td>
                <?
                if ($this->max_personal_parent_cnt>0) {
                    for($j=2;$j<=$this->max_personal_parent_cnt;$j++) {
                        echo '<td>'._IL('ARR_deps')->recs_names[$rec['personal_parent'.($j+2)]].'</td>';
                    }
                }
                ?>
                <td><?echo $rec['mo_before_cnt']?></td>
                <td><?echo $rec['mo_after_cnt']?></td>
                <td><?echo $rec['date_without_after_mo']?></td>
            </tr><?
        }
      ?></table><?

     //damp_array($rec,1,-1) ;
  }

    function print_template_CSV($list_recs,$options=array())
    {
        $i=0 ;
      if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {
          $data=array() ;

          $data['ФИО сотрудника']=$rec['member_name']?$rec['member_name']:'' ;
          $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name']?_IL('IL_works')->recs[$rec['working']]['obj_name']:'' ;
          $data['Организация']=$rec['_org_name']?$rec['_org_name']:'' ;
          $data['Подразделение']=$rec['_otdel_name']?$rec['_otdel_name']:'' ;
          if ($this->max_personal_parent_cnt>0) {
            for($j=2;$j<=$this->max_personal_parent_cnt;$j++) {
                $data['Подразделение (уровень '.$j.')']=_IL('ARR_deps')->recs_names[$rec['personal_parent'.($j+2)]];
            }
          }
          $data['Кол-во предсменных осмотров']=$rec['mo_before_cnt']?$rec['mo_before_cnt']:'' ;
          $data['Кол-во послесменных осмотров']=$rec['mo_after_cnt']?$rec['mo_after_cnt']:'' ;
          $data['Даты, в которые работник не прошел послесменный осмотр']=$rec['date_without_after_mo']?str_replace('<br>',' ',$rec['date_without_after_mo']):'' ;

          if (_sizeof($data)) foreach($data as $fname=>$value) $data[$fname]=iconv('UTF-8','windows-1251',$value) ;
          // для первой строки выводим заголовки
          if (!$i)
          {   $arr_title=array_keys($data) ;
              foreach($arr_title as $i=>$title) $arr_title[$i]=iconv('UTF-8','windows-1251',$title) ;
              fputcsv($this->file_csv,$arr_title,';');
          }
          // вывод данных
          fputcsv($this->file_csv,$data,';');
          $i++ ;
        }

    }


}
?>
