<?
/*по этому отчему вопрос - показывать ли сотрудников, которые не проходили МО в выбранной группе*/

class report_itog7 extends c_report
{  var $title='Статистика прохождения МО' ;
   var $filter=array() ;
   //var $url_report='/cab/reports/itog6/' ;
   public $use_fusioncharts=1 ;
   //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
   var $recs_org ;
   var $mo_data_min ;
   var $mo_data_max ;
    public $view_by_space_filter=0 ;

   function setting()
   { $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;
     $this->mo_data_min=$data_info['min_data'] ;
     $this->mo_data_max=$data_info['max_data'] ;
     $t=$this->mo_data_min ;
     if ($this->mo_data_max>$this->mo_data_min) while($t<$this->mo_data_max)
        {   $ts=getdate($t) ;
            $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
            $arr_from[$cur_month]=get_month_year($cur_month,'month year') ;
            $cur_month=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
            $arr_to[$cur_month]=get_month_year($cur_month,'month year') ;
            $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
        }

     $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">
                       <div class="row">
                           <? $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].' МО:',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_select('time_from','С, месяц:',2,$arr_from) ;
                              $this->filter_section_select('time_to','По, месяц:',2,$arr_to) ;
                           ?>
                           <section class="col col-2">
                               <label class="label">Параметры отображения:</label>
                               <label class="radio"><input type="radio" name="filter[view_pers]" value="0" <?if (!$this->filter['view_pers']) echo 'checked'?>><i></i>Подразделения</label>
                               <label class="radio"><input type="radio" name="filter[view_pers]" value="1" <?if ($this->filter['view_pers']) echo 'checked'?>><i></i>Сотрудники</label>
                           </section>
                   </div>
               </fieldset>
               <?$this->panel_buttons();?>
           </form>
        </div>
     <?
   }

 function get_arr_info_filters()
 { $info=parent::get_arr_info_filters() ;
   //if ($this->filter['time_int'])                        $info['временной интервал']=$this->time_int[$this->filter['time_int']] ;
   return $info ;
 }


function HTML_report_body($options=array())
{   if (!$this->filter['dep_id']) $this->filter['dep_id']=1 ;
    $rec_dep=execSQL_van('select t1.pkey,t1.obj_name,(select count(t2.pkey) from obj_site_personals t2 where t2.parent=t1.pkey and t2.clss=208 and t2.enabled=1) as cnt_child from obj_site_personals t1 where t1.clss=208 and t1.pkey='.$this->filter['dep_id']) ;
    if (!$this->filter['view_pers'] and !$rec_dep['cnt_child']) $this->filter['view_pers']=1 ;
    $result=$this->prepare_result_data() ;
    //damp_array($result,1,-1) ;
    ?><div id="reports_itog1"><?
      if (!$this->filter['view_pers']) $this->report_by_deps($result) ;
      else                             $this->report_by_pers($result) ;
    ?></div><?
}

function prepare_result_data()
{      if (!$this->filter['time_from'])
        { $ts=getdate($this->mo_data_min) ;
          $this->filter['time_from']=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;;
        }

        if (!$this->filter['time_to'])
        { $ts=getdate($this->mo_data_max) ;
          $this->filter['time_to']=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;;
        }

        $result2=array() ;
        $tf=getdate($this->filter['time_from']) ;
        $tt=getdate($this->filter['time_to']) ;
        $this->step=($tf['mon']==$tt['mon'] and $tf['year']==$tt['year'])? '1d':'1m' ;



        $t=$this->filter['time_from'] ;
        while($t<=$this->filter['time_to'])
        {
            $ts=getdate($t) ;   $t1=$t ;
            $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
            $arr_month[$cur_month]=get_month_year($cur_month,'month year') ;
            switch($this->step)
            { case '1d': $t=mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year']) ; $t2=$t-1; break  ;
              case '1m': $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ; $t2=$t-1; break  ; break ;
              default:   $t=$this->filter['time_to'] ;$t2=$t ;
            }

            $_usl=array() ;
            $_usl[]='model>0' ;
            $_usl[]='c_data>='.$t1 ;
            $_usl[]='c_data<='.$t2 ;
            if ($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']]))  $_usl[]='group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')' ;
            if ($this->filter['tk']==1)         $_usl[]='tk=0' ;
            if ($this->filter['tk']==2)         $_usl[]='tk=1' ;
            if ($this->filter['tk']==3)         $_usl[]='tk=2' ;
            if ($this->filter['dep_id'])
            { $cur_level=execSQL_value('select level from obj_site_personals where pkey='.$this->filter['dep_id']) ;
              $_usl[]='personal_parent'.$cur_level.'='.$this->filter['dep_id'] ;
              $fname='personal_parent'.($cur_level+1) ;
            }
            $usl=implode(' and ',$_usl) ;

            //echo date('d.m.Y H:i:s',$t1).' - '.date('d.m.Y H:i:s',$t2).'<br>' ;
            //$res=execSQL_van('select ')   ;
            if (!$this->filter['view_pers']) $result2[date('d.m.Y',$t1)]=execSQL_row('select '.$fname.',count(pkey) from view_mo_session where '.$usl.' group by '.$fname) ;
            else                             $result2[date('d.m.Y',$t1)]=execSQL_row('select member_id,count(pkey) as cnt from view_mo_session where '.$usl.' group by member_id having cnt>0') ;


        }
    //damp_array($result2,1,-1) ;
    return($result2) ;
}


function report_by_deps($result)
   {
       $recs=execSQL('select t1.pkey,t1.obj_name,(select count(t2.pkey) from obj_site_personals t2 where t2.parent=t1.pkey and t2.clss=208 and t2.enabled=1) as cnt_child from obj_site_personals t1 where t1.clss=208 and t1.parent='.$this->filter['dep_id']) ;

       ?><table class="basic fz_small auto full">
           <tr>
               <th>№</th>
               <th>Подразделение</th>
               <? if (_sizeof($result)) foreach($result as $data=>$rec_stats)
               {   $time_s=strtotime($data) ;
                   ?><th style="width:40px;"><?
                   switch($this->step)
                      { case '1d': echo date('d',$time_s) ; break  ;
                        case '1m': echo get_month_year($time_s,'month year') ; break ;
                        default:   echo get_month_year($time_s,'month year') ;
                      } ;
                   ?></th><?
               }?>
               <th>Итого</th>
           </tr>
       <?
       $i=1 ;
       if (_sizeof($recs)) foreach($recs as $rec_dep)
       {  ?><tr>
              <td><?echo $i?></td>
              <td class="left"><?   echo '<a href="'.$this->get_filter_to_params(array('dep_id'=>$rec_dep['pkey'],'view_pers'=>((!$rec_dep['cnt_child'])? 1:0))).'">'.$rec_dep['obj_name'].'</a>'?></td>
              <? $cnt=0 ; if (_sizeof($result)) foreach($result as $date=>$rec_stats) {?><td><?if ($rec_stats[$rec_dep['pkey']]) echo '<a target=_blank href="'.$this->get_filter_to_params(array('dep_id'=>$rec_dep['pkey'],'view_pers'=>((!$rec_dep['cnt_child'])? 1:0)),array('url_report'=>'/cab/reports/report_mo_sess/')).'">'.$rec_stats[$rec_dep['pkey']].'</a>' ; $cnt+=$rec_stats[$rec_dep['pkey']] ;?></td><?} ?>
              <td><?if ($cnt) echo $cnt?></td>
           </tr><?
           $i++ ;
       }
       ?></table><?
   }

  function report_by_pers($result)
   {   if (!$this->filter['dep_id']) $this->filter['dep_id']=1 ;
       $rec_dep=execSQL_van('select pkey,obj_name,level from obj_site_personals where pkey='.$this->filter['dep_id']) ;
       $recs=execSQL('select pkey,obj_name,dr from obj_site_personals where clss=211 and parent'.$rec_dep['level'].'='.$this->filter['dep_id']) ;
       //echo '$this->step='.$this->step.'<br>' ;
       ?><table class="basic fz_small auto full">
           <tr>
               <th>№</th>
               <th>ФИО</th>
               <? if (_sizeof($result)) foreach($result as $data=>$rec_stats)
               {   $time_s=strtotime($data) ;
                   ?><th style="width:40px;"><?
                   switch($this->step)
                      { case '1d': echo date('d',$time_s) ;break  ;
                        case '1m': echo get_month_year($time_s,'month year') ; break ;
                        default:   echo get_month_year($time_s,'month year') ;
                      } ;
                   ?></th><?
               }?>
               <th>Итого</th>
           </tr>
       <?
       $i=1 ;
       if (_sizeof($recs)) foreach($recs as $rec_pers)
       {  ?><tr>
              <td><?echo $i?></td>
              <td class="left"><? echo '<a target=_blank href="'.$this->get_filter_to_params(array('personal_id'=>$rec_pers['pkey'],'view_pers'=>((!$rec_pers['cnt_child'])? 1:0)),array('url_report'=>'/cab/reports/report_mo_sess/')).'">'.$rec_pers['obj_name'].'</a>'?></td>
              <? $cnt=0 ; if (_sizeof($result)) foreach($result as $date=>$rec_stats)
              {     $time_from=strtotime($date) ;
                    $ts=getdate($time_from) ;
                    switch($this->step)
                    { case '1d': $time_to=mktime(23,59,59,$ts['mon'],$ts['mday'],$ts['year']) ; break  ;
                      case '1m': $time_to=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ; break ;
                    } ;
                  ?><td><?if ($rec_stats[$rec_pers['pkey']]) echo '<a target=_blank href="'.$this->get_filter_to_params(array('personal_id'=>$rec_pers['pkey'],'time_from'=>$time_from,'time_to'=>$time_to,'model_all'=>1),array('url_report'=>'/cab/reports/report_mo_sess/')).'">'.$rec_stats[$rec_pers['pkey']].'</a>' ;
                          $cnt+=$rec_stats[$rec_pers['pkey']] ;
                  ?></td><?

              } ?>
              <td><?if ($cnt) echo $cnt?></td>
           </tr><?
           $i++ ;
       }
       ?></table><?
   }

function report_by_pers2($result)
   {   // получаем ID всех организаций, прошедших МО в заданном переоде

       if (!$this->filter['dep_id'])
       { $title='Организация' ;
         $arr=execSQL_row('select distinct(_org_id),_org_name from view_mo_session where c_data>='.$this->filter['time_from'].' and c_data<='.$this->filter['time_to'].' and model>0 order by _org_name') ;

       }
       else
       { $title='Сотрудники организации "'.$this->recs_org[$this->filter['org_id']]['obj_name'].'"' ;
         $usl_group=($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']]))?  ' and group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')':'' ;
         $arr=execSQL_row('select distinct(member_id),member_name from view_mo_session where c_data>='.$this->filter['time_from'].' and c_data<='.$this->filter['time_to'].' and model>0 and _org_id='.$this->filter['org_id'].$usl_group.' order by member_name') ;
       }

       ?><table class="basic fz_small auto" style="table-layout:auto;width:100%;">
               <tr><th>№</th><th style="width:300px;"><?echo $title?></th>
                   <? if (_sizeof($result)) foreach($result as $data=>$rec)
                   {   $time_s=strtotime($data) ;
                       ?><th style="width:40px;"><?
                       switch($this->step)
                                   { case '1d': echo date('d',$time_s) ; break  ;
                                     case '1m': echo get_month_year($time_s,'month year') ; break ;
                                     default:   echo get_month_year($time_s,'month year') ;
                                   } ;
                       ?></th><?
                   }
                  ?>
                  <th>Итого</th>
               </tr>

           <? $row_summ=array() ; $cnt_all=array() ; $i=1 ;
              if (_sizeof($arr)) foreach($arr as $id=>$name)
               {   //$time_s=strtotime($data) ;
                   //$ts=getdate($time_s) ;
                   //$time_e=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;  // исправлено
                   //$time_e=($this->step=='1d')? mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year'])-1:mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
                   //$url_report_detail=($this->step=='1d')? '/cab/reports/report_mo_sess/':'/cab/reports/itog6/' ;

                   ?><tr>
                     <td><?echo $i ; $i++ ;?></td>
                     <td class="left" style="width:300px;"><?echo $name?></td>
                     <?
                        if (_sizeof($result)) foreach($result as $data=>$rec) {?><td style="width:40px;"><?echo $rec[$id] ; $cnt_all[$data]+=$rec[$id] ; $row_summ[$id]+=$rec[$id] ;?></td><?} ?>
                     <td class="center bold"><?echo $row_summ[$id]?></td>
                    </tr>
                   <?
               }
               ?><tr class="itog">
                   <td class="left"></td>
                   <td class="left">ИТОГО</td>
                    <? if (_sizeof($result)) foreach($result as $data=>$rec) { ?><td><?if ($cnt_all[$data]>0) echo $cnt_all[$data]?></td><?} ?>
                   <td><?$sum=array_sum($row_summ) ; if ($sum) echo $sum ;?></td>
               </tr>
             </table>
       <br>
       <br>
             <style type="text/css">
                 div#reports_itog1{}
                 div#reports_itog1 table{width:100%;table-layout:auto;border-collapse:collapse;}
                 div#reports_itog1 th{background:#dddddd;color:black;font-weight:bold;border:1px solid #aaaaaa;}
                 div#reports_itog1 td{padding:5px;border:1px solid #aaaaaa;text-align:center;}
                 div#reports_itog1 td.left{text-align:left;}
                 div#reports_itog1 tr.subitog1 td{font-weight:bold;background:#f1f1f1;text-align:center;}
                 div#reports_itog1 tr.subitog1 td.left{text-align:left;}
                 div#reports_itog1 tr.subitog2 td{font-weight:bold;background:#fafafa;text-align:center;}
                 div#reports_itog1 tr.subitog2 td.left{text-align:left;}
                 div#reports_itog1 tr.itog td{font-weight:bold;background:#dddddd;}
                 div#reports_itog1 table.debug td:first-child{width:250px;text-align:left;}
                 div#reports_itog1 table.debug td:last-child{width:70px;}
              </style>
     <?

   }

function _print_template_CSV($list_recs,$options=array())
        { $i=$options['from'] ;
          if (_sizeof($list_recs)) foreach($list_recs as $d=>$rec)
            { $data=array() ;
              $data['Дата']=$d ;
              $data['Кол-во МО']=$rec['count_mo'] ;
              $data['Терминалы - МО пройден']=$rec['mo_stats'][1]+$rec['mo_stats'][3] ;
              $data['Терминалы - МО не пройден, уклонились от РМВ']=$rec['mo_stats'][2]+$rec['mo_stats'][4] ;

              $data['РМВ - Причины - Давление']=$rec['d'][0] ;
              $data['РМВ - Причины - Пульс']=$rec['p'][0] ;
              $data['РМВ - Причины - Температура']=$rec['t'][0] ;
              $data['РМВ - Причины - Алкоголь']=$rec['a'][0] ;
              $data['РМВ - Причины - Пупиллометрия']=$rec['n'][0] ;
              $data['РМВ - Причины - Жалобы']=$rec['q'][0] ;
              $data['РМВ - Причины - Не удалось провести измерение']=$e=$rec['error'][0] ;
              $data['РМВ - МО пройден']=$a3=$rec['mo_stats'][5]+$rec['mo_stats'][7]+$rec['mo_stats'][9] ;
              $data['РМВ - Допуск запрещен']=$a4=$rec['mo_stats'][6]+$rec['mo_stats'][8]+$rec['mo_stats'][10] ;
              $data['Среднее время МО']=round($rec['avg_time']) ;
              $data['КРТ']=number_format(round(($a3+$a4)/$rec['count_mo']*100,2),2,',','') ; ;
              $data['КОC']=number_format(round($e/$rec['count_mo']*100,2),2,',','')  ;

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

        }

}

?>
