<?php
class report_training extends c_report
{
 var $title='Отчет о прохождении ежегодных занятий' ;
 var $view_by_space_filter=1 ;
 var $event_id=0 ;
 var $personal_id=0 ;
 var $rec_personal=array() ;
 var $rec_event=array() ;
 var $sign_before_print=1 ;
 var $allow_export_to_csv=1 ;

 function init($options=array())
 { if ($this->event_id) $this->rec_event=EVENTS()->get_event_by_id($this->event_id)  ;
  // if ($this->personal_id) $this->rec_personal=PERSONAL()->get_personal_by_id($this->personal_id)  ;
  // if ($this->filter['name'])
  // { $this->rec_personal=PERSONAL()->get_personal_by_name($this->filter['name'])  ;
  //   $this->personal_id=$this->rec_personal['pkey'] ;
  // }
   if ($this->filter['event_id'])
   { $this->rec_event=EVENTS()->get_event_by_id($this->filter['event_id'])  ;
     $this->event_id=$this->rec_event['pkey'] ;
   }
 }
 function setting($options=array())
 {   $arr_instruktions=execSQL('select pkey,obj_name from obj_site_events_schedule where clss=222 and obj_name!="" and ext like "%instruction/i_event_training%" order by c_data desc') ;

     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']]) ;

     $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
     ?><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">
                          <? if (!$options['no_view_event_select']) $this->filter_section_select('event_id','Мероприятия:',2,$arr_instruktions) ;
                             $this->filter_section_select('lession_group_id','Место проведения мероприятия:',2,$arr_groups) ;
                             $this->filter_section_input_text('data_from','Дата занятий, от:',2,array('class'=>'datepicker')) ;
                             $this->filter_section_input_text('data_to','Дата занятий,До:',2,array('class'=>'datepicker')) ;
                          ?>
                        </div>
                        <div class="row">
                          <?$this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                            $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_select_multiple('working_ids','Должность:',2,$arr_workd_ids) ;
                          ?>
                      </div>

                  </fieldset>
                  <?$this->panel_buttons($options);?>
              </form>
       </div><br>
     <?
  }

    function setting_small($options=array())
         {
           //damp_array(ENGINE()->reports_list['napravlenie']['']) ;
              ?><div id="panel_filter">
                     <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                          <?$this->panel_buttons($options);?>
                      </form>
               </div><br>
             <?
         }



    function _panel_buttons($options=array())
         { ?><div id="panel_buttons"><input type="submit" class="button v2" cmd="set_filter" value="<?echo ($this->editing)? 'Получить данные':'Сформировать отчет'?>">&nbsp;&nbsp;<?
             if ($options['hidden_params']) foreach($options['hidden_params'] as $name=>$value) echo '<input type="hidden" name="'.$name.'" value="'.$value.'">' ;
           if (!$this->editing)
           //$doc_report_url=$this->get_filter_to_params(array('event_id'=>$this->event_id),array('url_report'=>'/cab/reports/report_training/')) ;
           {?><button class="button v2" cmd="docs/doc_create" report_code="<?echo $this->report_class?>">Сохранить в документах</button>&nbsp;&nbsp;<??>
                                <!--<button class="button v2" cmd="report/view_as_html">HTML</button>&nbsp;&nbsp;-->
                                <!--<button class="button v2" cmd="report/view_as_pdf" mode="<?echo $this->PDF_master?>">PDF</button>&nbsp;&nbsp;-->
                                <?if ($this->allow_export_to_excel){?><button class="button v2" cmd="report/view_as_xls">Excel</button>&nbsp;&nbsp;<?}?>
                                <?if ($this->allow_export_to_csv){?><button class="button v2" cmd="report/view_as_CSV">Excel CSV</button>&nbsp;&nbsp;<?}?>
                                <?if ($this->allow_set_to_cron){?><button class="button v2" cmd="report/set_report_to_cron" report_code="<?echo $this->report_class?>">Планировщик</button>&nbsp;&nbsp;<?}?>
                                <!--<button class="button v2" cmd="report/to_print">Печать</button>&nbsp;&nbsp;-->
                                <?$this->panel_report_buttons();?>
                              <?}
           ?></div><?
         }


    function create_usl_select_obj($_params,&$options)
   {  //damp_array($this->filter,1,-1) ;
      $usl=array() ;
      $usl[]='event_id='.$this->event_id ;
      $usl[]='lession_person_status=4';
      //if ($this->ids)              $usl[]='pkey in ('.$this->ids.')' ;
      if ($this->filter['name'])              $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
      if ($this->filter['personal_id'])       $usl[]='pkey='.$this->filter['personal_id'].'' ;
      if ($this->filter['lession_id']) $usl[]='lession_id='.$this->filter['lession_id'] ;
      if ($this->filter['personal_id'])        $usl[]='personal_id='.$this->filter['personal_id'] ;
      if ($this->filter['data_from'])        $usl[]='lession_time_from>='.strtotime($this->filter['data_from']) ;
      if ($this->filter['data_to'])          $usl[]='lession_time_from<='.strtotime($this->filter['data_to']) ;
      if ($this->filter['lession_group_id'])        $usl[]='lession_group_id='.$this->filter['lession_group_id'] ;
      if ($this->filter['name'])            $usl[]='obj_name like "%'.$this->filter['name'].'%"' ;
      if ($this->filter['dep_ids'])         $usl[]='parent2 in ('.implode(',',array_keys($this->filter['dep_ids'])).')' ;
      if ($this->filter['otdel_ids'])       $usl[]='parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
      if (_sizeof($this->filter['working_ids'])) $usl[]='working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;
      // в этом журнале не должно быть ограничения по видимости сотрудников, так как он показывает список уже прошедших занятие
      if (MEMBER()->personal_viewer_name) $usl['account_personal_filter']='(lession_group_id in ('.MEMBER()->cur_groups_visible.') or  pkey in (select pkey from '.MEMBER()->personal_viewer_name.'))' ;



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

   function panel_info_filter()
    { $_str=array() ; $title='' ;  $info=array() ;
      if ($this->filter['lession_group_id'])   $info['Место проведения']=ACCOUNTS()->get_member_name_by_id($this->filter['lession_group_id'])  ;
      if ($this->event_id)
      { $arr_names=execSQL_line('select obj_name from obj_site_events_schedule where pkey='.$this->event_id) ;
        $info['Мероприятие']=implode(', ',$arr_names) ;
      }
      $info2=$this->get_arr_info_filters() ;
      $info=array_merge($info,$info2) ;
      if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
      if (_sizeof($_str)) $title='<div class=center>'.implode(' ',$_str).'</div>' ;
      return $title ;
      }



   function get_cnt_items($usl,$options=array())
   { //$options['debug']=2 ;
     $cnt=execSQL_value('select count(distinct(pkey)) from  view_lession_personals 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 c_data desc' ;
     //echo $usl ;
      // $options['debug']=2 ;
  	  $personal_ids=execSQL_line('select distinct(pkey) from view_lession_personals where '.$usl.$limit,$options) ;
  	  if (_sizeof($personal_ids))
      {   $options['no_indx']=1 ;
          $list_recs=execSQL('select * from view_personals where pkey in ('.implode(',',$personal_ids).')',$options) ;
          //$list_recs_by_person=group_by_field('personal_id',$list_recs) ;
        //$personal_lession=execSQL('select * from obj_site_lession_persons where personal_id in ('.implode(',',$personal_ids).')',$options) ;
      }
  	  else $list_recs=array() ;
     if (_sizeof($list_recs)) foreach($list_recs as $id=>$rec) PERSONAL()->prepare_public_info_to_personal_v2($list_recs[$id],$options) ;
     return($list_recs) ;
   }


     // шаблон - вывод ссылками без разделитея
     function print_template_HTML($list_recs,$options=array())
       { $id=($options['id'])? 'id='.$options['id']:'' ;

         // массив всех тем обучения
         $event_themes=execSQL('select  pkey,obj_name from obj_site_events_themes where parent='.$this->event_id,0) ;
         //print_2x_arr($event_themes) ;
         // массив тем, которые были пройдены на занятиях
         $lession_themes=execSQL('select parent as lession_id,theme_id from obj_site_lession_themes where event_id='.$this->event_id,0,1) ;
         if (_sizeof($lession_themes)) foreach($lession_themes as $rec) $lession_theme[$rec['lession_id']][]=$rec['theme_id'] ;
         //damp_array($lession_theme,1,-1) ;
         // массив участия сотрудников в занятиях
         $personal_lession=execSQL('select personal_id,parent as lession_id,c_data from obj_site_lession_persons where event_id='.$this->event_id.' and status=4',array('no_indx'=>1,'debug'=>0)) ;
         // надо проставить у сотрудников статус тем, темы проходились на разных занятиях
         $personal_themes=array() ;
         if (_sizeof($personal_lession)) foreach($personal_lession as $rec)
         {   $lession_id=$rec['lession_id'] ;
             $personal_id=$rec['personal_id'] ;
             if (_sizeof($lession_theme[$lession_id])) foreach($lession_theme[$lession_id] as $theme_id)
                 if (!isset($personal_themes[$personal_id][$theme_id])) $personal_themes[$personal_id][$theme_id]=$rec['c_data'];
                 else if ($rec['c_data']>$personal_themes[$personal_id][$theme_id]) $personal_themes[$personal_id][$theme_id]=$rec['c_data'] ;
         }
         //damp_array($personal_themes) ;
         $i=0 ;
         ?><table class="report_personals_training basic fz_small full auto"<?echo $id?>>
            <thead>
             <tr><th rowspan="2">№</th><th rowspan="2">Фамилия Имя Отчество</th><th rowspan="2">Организация</th><th rowspan="2">Дата рождения</th><th colspan="<?echo _sizeof($event_themes)?>">Наименования тем</th><th rowspan="2">Дата зачета</th><th rowspan="2">Зачет/Не зачет</th></tr>
             <tr><?if (_sizeof($event_themes)) foreach($event_themes as $rec_theme) echo '<th class="small">'.$rec_theme['obj_name'].'</th>'?></tr>
            </thead>
           <tbody>
           <?
             if (_sizeof($list_recs)) foreach($list_recs as $rec)
             {   $personal_id=$rec['pkey'] ;
                 $i++ ;
                 ?><tr class=item>
                     <td><?echo $i?></td>
                     <td class="left"><a href="<?echo $rec['__href_window']?>" class="new_window" target="_blank" title="win_second"><?echo $rec['obj_name']?></a></td>
                     <td class="left"><?echo $rec['_org_name'].'<br>'.$rec['_otdel_name']?></td>
                     <td class="left"><?echo $rec['dr']?></td>
                     <? $last_date_str='' ;
                        if (_sizeof($event_themes)) foreach($event_themes as $rec_theme)
                        {
                            $theme_id=$rec_theme['pkey'] ;
                            $last_date=$personal_themes[$personal_id][$theme_id] ;
                            $last_date_str=($last_date)? date('d.m.Y',$last_date):'' ;
                            echo '<td>'.$last_date_str.'</td>' ;
                        }
                        $max_data=(_sizeof($personal_themes[$personal_id]))? max($personal_themes[$personal_id]):0 ;
                        $max_date_str=($max_data)? date('d.m.Y',$max_data):'' ;
                     ?>
                     <td><?echo (_sizeof($personal_themes[$personal_id])>=_sizeof($event_themes))? $max_date_str:'-'?></td>
                     <td><?echo (_sizeof($personal_themes[$personal_id])>=_sizeof($event_themes))? 'Зачет':'Незачет'?></td>
                 </tr><?
             }
           ?></tbody></table>
             <style type="text/css">
                 table{-fs-table-paginate: paginate;}
                 table.report_personals_training th.small{font-size:10px;font-weight: normal;line-height:1em;vertical-align:top;text-align:left;}
                 thead {display: table-header-group;break-inside:avoid}
             </style>
           <?
       }

  function print_template_CSV($list_recs,$options=array())
     { $i=$options['from'] ;
      $this->init() ;

       // массив всех тем обучения
       $event_themes=execSQL('select  pkey,obj_name from obj_site_events_themes where parent='.$this->event_id,0) ;
       //print_2x_arr($event_themes) ;
       // массив тем, которые были пройдены на занятиях
       $lession_themes=execSQL('select parent as lession_id,theme_id from obj_site_lession_themes where event_id='.$this->event_id,0,1) ;
       if (_sizeof($lession_themes)) foreach($lession_themes as $rec) $lession_theme[$rec['lession_id']][]=$rec['theme_id'] ;
       //damp_array($lession_theme,1,-1) ;
       // массив участия сотрудников в занятиях
       $personal_lession=execSQL('select personal_id,parent as lession_id,c_data from obj_site_lession_persons where event_id='.$this->event_id.' and status=4',array('no_indx'=>1,'debug'=>0)) ;
       // надо проставить у сотрудников статус тем, темы проходились на разных занятиях
       $personal_themes=array() ;
       if (_sizeof($personal_lession)) foreach($personal_lession as $rec)
       {   $lession_id=$rec['lession_id'] ;
           $personal_id=$rec['personal_id'] ;
           if (_sizeof($lession_theme[$lession_id])) foreach($lession_theme[$lession_id] as $theme_id)
               if (!isset($personal_themes[$personal_id][$theme_id])) $personal_themes[$personal_id][$theme_id]=$rec['c_data'];
               else if ($rec['c_data']>$personal_themes[$personal_id][$theme_id]) $personal_themes[$personal_id][$theme_id]=$rec['c_data'] ;
       }

       if (_sizeof($list_recs)) foreach($list_recs as $rec) //if ($rec['event_pass_id'])
         {  $personal_id=$rec['pkey'] ;
           $data=array() ;
           //$data['№']=$rec['event_pass_id'] ;
           //$data['АТП']=($rec['event_group_id'])? $rec['event_pass_group_name']:'' ;
           $data['Организация']=$rec['_org_name'] ;
           $data['Подразделение']=$rec['_otdel_name'] ;
           $data['ФИО']=$rec['obj_name'] ;
           $data['ДатаРожд']=$rec['dr'] ;


          if (_sizeof($event_themes)) foreach($event_themes as $rec_theme)
               {
                    $theme_id=$rec_theme['pkey'] ;
                    $last_date=$personal_themes[$personal_id][$theme_id] ;
                    $last_date_str=($last_date)? date('d.m.Y',$last_date):'' ;
                    $data[$rec_theme['obj_name']]=$last_date_str ;

               }
           $max_data=(_sizeof($personal_themes[$personal_id]))? max($personal_themes[$personal_id]):0 ;
           $max_date_str=($max_data)? date('d.m.Y',$max_data):'' ;

           $data['Дата зачета']=(_sizeof($personal_themes[$personal_id])>=_sizeof($event_themes))? $max_date_str:'-' ;
           $data['Результат зачета']=(_sizeof($personal_themes[$personal_id])>=_sizeof($event_themes))? 'Зачет':'Незачет' ;


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

     }

}

?>
