<?php
class report_itog4 extends c_report
{  var $title='Общий отчет по отстранениям' ;
   var $filter=array() ;
   var $mo_models=array(6,8,10) ;  //  '2,4,6,8,10'
   //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
   var $data=array() ;
   var $itog=array() ;

  function setting()
  { $now=getdate() ;
    if (!$this->filter['data_from']) $this->filter['data_from']=date('d.m.Y',mktime(0,0,0,$now['mon'],1,$now['year']));
    if (!$this->filter['data_to'])   $this->filter['data_to']=date('d.m.Y',mktime(0,0,0,$now['mon']+1,1,$now['year'])-1);

    $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_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('tk','Тип контроля:',2,$_SESSION['ARR_mo_tk_type'],array('use_id_plus_1'=>1)) ;
                               $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                               $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                            ?>
                        </div>
                    </fieldset>
                    <?$this->panel_buttons();?>
                </form>
        </div>
    <?
  }

 function get_arr_info_filters()
 { $info=parent::get_arr_info_filters() ;
   //if ($this->filter['min_mo'])  $info['Минимальное число МО']=$this->filter['min_mo'] ;
   //if ($this->filter['min_proc'])  $info['Пороговый процент']=$this->filter['min_proc'] ;
   return $info ;
 }

function create_usl_select_obj($_params,&$options=array())
 {  $_usl=array() ;
    $_usl[]='model in (6,8,10)' ;
    if ($this->filter['data_from']) $_usl[]='c_data>='.strtotime($this->filter['data_from']) ;
    if ($this->filter['data_to'])   $_usl[]='c_data<='.strtotime($this->filter['data_to']) ;
    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=3' ;
    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'] ;
    }
    if ($this->filter['org_ids'])       $_usl[]='personal_parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
    if ($this->filter['otdel_ids'])     $_usl[]='personal_parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;

    if (!$options['dont_use_member_personal_filter'] and MEMBER()->personal_viewer_name) $_usl['account_personal_filter']='personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;

    $usl_res=implode(' and ',$_usl) ;
    return($usl_res) ;
 }

function prepare_data($options=array())
{
    $usl=$this->create_usl_select_obj(array()) ;
    $recs=execSQL('select * from view_mo_session where '.$usl.' order by personal_parent1,personal_parent2,personal_parent3',array('debug'=>0)) ;
    //$usl.=' and personal_parent2=9251 and res_a>1' ;
    //$recs=execSQL('select * from view_mo_session where '.$usl.' order by personal_parent1,personal_parent2,personal_parent3',array('debug'=>2)) ;

    $result=array() ;
    // получаем id персонала, отстраннего по результам МО
    if (_sizeof($recs)) foreach($recs as $rec_mo) // для моделей 6,8,10 всегда будет dopusk=2 // if (!$rec_mo['dopusk'] or $rec_mo['dopusk']==2)
    {   if ($rec_mo['res_a']>1)  $result[$rec_mo['personal_parent']]['alko']++  ;    // если не был пройден алкотест
        else if ($rec_mo['res_s']>1 or $rec_mo['res_d']>1 or $rec_mo['res_p']>1) $result[$rec_mo['personal_parent']]['ssz']++  ; //
        else $result[$rec_mo['personal_parent']]['other']++  ;   // если нет никакого решения по допуску - клиент не прошел МО до конца
    }

    $i=1 ; $this->itog=array() ;
    //damp_array($result,1,-1) ;

    if (_sizeof($result)) foreach($result as $org_id=>$info)
     {   $this->data[$i]['col1']=$i ;
         $this->data[$i]['col2']=PERSONAL()->get_full_dep_name_by_dep_id($org_id)  ;
         if ($info['alko'])
         { $url_filter=$this->get_filter_to_params(array('dep_id'=>$org_id,'a'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')) ;
           $this->data[$i]['col3']='<a target=blank href="'.$url_filter.'">'.$info['alko'].'</a>' ;
           $this->itog['alko']+=$info['alko'] ;
         }
         if ($info['ssz'])
         { $url_filter=$this->get_filter_to_params(array('dep_id'=>$org_id,'ssz'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')) ;
           $this->data[$i]['col4']='<a target=blank href="'.$url_filter.'">'.$info['ssz'].'</a>' ;
           $this->itog['ssz']+=$info['ssz'] ;
         }
         if ($info['other'])
         { $url_filter=$this->get_filter_to_params(array('dep_id'=>$org_id,'other'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')) ;
           $this->data[$i]['col5']='<a target=blank href="'.$url_filter.'">'.$info['other'].'</a>' ;
           $this->itog['other']+=$info['other'] ;
         }
         $i++ ;
      }
}

function HTML_report_body($options=array())
{   $this->prepare_data() ;
    //damp_array($result) ;
    ?><table class="basic fz_small full auto">
         <tr><th>№</th>
             <th>Организация, подразделение</th>
             <th>Отстранено по алкоголю</th>
             <th>Отстранено по ССЗ</th>
             <th>Отстранено по другим причинам</th>
         </tr>
     <? $i=1 ; $this->itog=array() ;
        if (_sizeof($this->data)) foreach($this->data as $rec)
         {   ?><tr><td><?echo $rec['col1']?></td>
                   <td class="left"><?echo $rec['col2'] ?></td>
                   <td><? echo $rec['col3'] ?></td>
                   <td><? echo $rec['col4'] ?></td>
                   <td><? echo $rec['col5'] ?></td>
                </tr>
            <?
            $i++ ;
         }
       if (_sizeof($this->data))
       {?><tr class="itog">
              <td></td>
              <td>ИТОГО</td>
              <td><? if ($this->itog['alko']) echo '<a target=blank href="'.$this->get_filter_to_params(array('a'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')).'">'.$this->itog['alko'].'</a>' ; ?></td>
              <td><? if ($this->itog['ssz']) echo '<a target=blank href="'.$this->get_filter_to_params(array('ssz'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')).'">'.$this->itog['ssz'].'</a>' ; ?></td>
              <td><? if ($this->itog['other']) echo '<a target=blank href="'.$this->get_filter_to_params(array('other'=>1,'model'=>array(6,8,10)),array('url_report'=>'/cab/reports/report_mo3/')).'">'.$this->itog['other'].'</a>' ; ?></td>
          </tr><?}?>
       </table>
    <?
    if (!_sizeof($this->data)) {?><div class="alert" style="text-align:center">Данных по Вашему запросу не найдено</div><?}
}

function CSV_report_body($options=array())
  { $this->prepare_data($options) ;
    $i=0 ;
    if (_sizeof($this->data)) foreach($this->data as $rec)
    {     $data=array() ;
          $data['№']=$rec['col1'] ;
          $data['Организация, подразделение']=strip_tags(str_replace('<br>'," / ",$rec['col2']));
          $data['Отстранено по алкоголю']=strip_tags($rec['col3']) ;
          $data['Отстранено по ССЗ']=strip_tags($rec['col4']) ;
          $data['Отстранено по другим причинам']=strip_tags($rec['col5']) ;
          $this->put_data_to_CSV($data,$i) ;
          $i++ ;
    }
    $data=array() ;
    $data['№']='' ;
    $data['Подразделение']='ИТОГО' ;
    $data['Отстранено по алкоголю']=$this->itog['alko'];
    $data['Отстранено по ССЗ']=$this->itog['ssz'];
    $data['Отстранено по другим причинам']=$this->itog['other'];
    $this->put_data_to_CSV($data,$i) ;
  }


}

?>
