<?php
include_once(_DIR_EXT.'/aspmo_pp/i_source.php') ;
class report_pp_itog3 extends c_report
{
 var $title='Отчет по результатам пупиллометрии' ;
 var $filter=array() ;
 //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF

 // локальные переменные отчета
 var $arr_mo_to_orgs=array() ;
 var $rules=array() ;
 var $res=array() ;
 var $arr_org_names=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);

  ?><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">
                          <section class="col col-4">
                              <label class="label">Подразделениe:</label>
                              <label class="select">
                                   <select name="filter[dep_id]"><option value="0">Все</option>
                                     <? echo PERSONAL()->get_select_option(1,$this->filter['dep_id']) ;?>
                                   </select>
                              </label>
                          </section>
                          <?$arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206')?>
                          <section class="col col-2">
                              <label class="label">Группа:</label>
                              <label class="select">
                                  <select name="filter[group_id]"><option value="0">Все</option><?
                                    if (_sizeof($arr_groups)) foreach($arr_groups as $id=>$name) {?><option value="<?echo $id?>" <?if($this->filter['group_id']==$id) echo 'selected'?>><?echo $name?></option><?}?>
                                  </select>
                              </label>
                          </section>
                          <section class="col col-2">
                              <label class="label">От:</label>
                              <label class="input"><input type="text" name="filter[data_from]" class="datepicker" value="<?echo $this->filter['data_from']?>"></label>
                          </section>
                          <section class="col col-2">
                              <label class="label">До:</label>
                              <label class="input"><input type="text" name="filter[data_to]" class="datepicker" value="<?echo $this->filter['data_to']?>"></label>
                          </section>
                          <section class="col col-2">
                              <label class="label">Результат:</label>
                              <label class="select">
                                  <select name="filter[pp_result]"><option value="0">Все</option><?
                                      if (_sizeof($GLOBALS['pp_result'])) foreach($GLOBALS['pp_result'] as $id=>$name) {?><option value="<?echo $id+1?>" <?if($this->filter['pp_result']==($id+1)) echo 'selected'?>><?echo $name?></option><?}?>
                                  </select>
                              </label>
                          </section>
                      </div>
                  </fieldset>
                  <?$this->panel_buttons();?>
              </form>
      </div>
  <?
}

function panel_info_filter()
{ $_str=array() ; $info=array() ; $title='' ;
  //if ($this->filter['member'])                        $info['механик']=ACCOUNTS()->get_member_name_by_id($this->filter['member'] )  ;
  if ($this->filter['data_from'])                       $info['c']=$this->filter['data_from'] ;
  if ($this->filter['data_to'])                         $info['по']=$this->filter['data_to'] ;
  if ($this->filter['age_from'])                        $info['возраст c']=$this->filter['age_from'] ;
  if ($this->filter['age_to'])                          $info['возраст по']=$this->filter['age_to'] ;
  if ($this->filter['group_id'])                        $info['Группа терминалов']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
  if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
  if ($this->filter['tk'])                              $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;
  if ($this->filter['pp_result'])                       $info['Тип результата']=$GLOBALS['pp_result'][$this->filter['pp_result']-1]  ;
  if (_sizeof($this->filter['working']))  foreach($this->filter['working'] as $working_id=>$value) $info['Должность'][]=_IL('IL_works')->recs[$working_id]['obj_name'] ;
  //if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
  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='<div class=center>'.implode(' ',$_str).'</div>' ;
  return $title ;
}



function prepare_data($options=array())
{   $this->res=array() ; $this->arr_mo_to_orgs=array() ; $this->arr_org_names=array() ; $arr_work_names=array() ;  $cur_level=0 ;

    $this->rules=array() ;                                       // нижние значения идут через >=, верхние через <
    $arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206');

    $options['order']='indx,c_data asc' ;
    //if (_IS_SYSTEM_IP) $GLOBALS['debug_db']=1 ;
    $_usl=array() ;
    $_usl[]='model>0' ;
    if ($this->filter['data_from']) $_usl[]='c_data>='.strtotime($this->filter['data_from']) ;
    if ($this->filter['data_to']) {
        $arr=explode(' ',trim($this->filter['data_to'])) ;
        $time_to=(!$arr[1])? strtotime($this->filter['data_to'].' 23:59:59'):strtotime($this->filter['data_to']) ;
        $_usl[]='c_data<='.$time_to ;
    }
    if ($this->filter['age_from']) $_usl[]='personal_age>='.$this->filter['age_from'] ;
    if ($this->filter['age_to']) $_usl[]='personal_age<='.$this->filter['age_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['dep_id'])
    { $cur_level=execSQL_value('select level from obj_site_personals where pkey='.$this->filter['dep_id']) ;
      //echo 'dep_id='.$this->filter['dep_id'].' level='.$cur_level.'<br>' ;
      $_usl[]='personal_parent'.$cur_level.'='.$this->filter['dep_id'] ;
    }
    if ($this->filter['pp_result']>0) {
        if ($this->filter['pp_result']==7) $_usl[]='_pp_result is NULL';
        elseif ($this->filter['pp_result']==1)   $_usl[]='_pp_result="ok"';
        else $_usl[]='_pp_result="'.$GLOBALS['pp_result'][$this->filter['pp_result']-1].'"';
    }
    if (_sizeof($this->filter['working'])) $_usl[]='working in ('.implode(',',array_keys($this->filter['working'])).')' ;
    //damp_array($_usl,1,-1) ;

    $usl=implode(' and ',$_usl) ;
    $recs=execSQL('select pkey,model,working,member_pol,personal_age,_pp_result,parent,group_id,personal_parent1,personal_parent2,personal_parent3,personal_parent4,personal_parent5,personal_parent6,personal_parent7,personal_parent8,personal_parent9 from view_mo_session_pp where '.$usl,array('debug'=>0)) ;
    if (_sizeof($recs)) foreach($recs as $rec_mo)
    {
       // пропускаем МО через правила

       $age=$rec_mo['personal_age'];

        if ($age<18) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e1']++; $ok=1;}
        if ($age>=18 and $age<=19) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e2']++; $ok=1;}
        if ($age>=20 and $age<=29) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e3']++; $ok=1;}
        if ($age>=30 and $age<=39) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e4']++; $ok=1;}
        if ($age>=40 and $age<=49) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e5']++; $ok=1;}
        if ($age>49) {$this->res[$arr_groups[$rec_mo['group_id']]][$rec_mo['member_pol']]['e6']++; $ok=1;}

    }
}

function HTML_report_body($options=array())
{

    $this->prepare_data($options) ;

    ?><table class="basic fz_small full auto">
         <tr><th rowspan="2">№</th>
             <th rowspan="2">Группа</th>
             <th rowspan="2">Пол</th>
             <th colspan="6">Возраст</th>
             <th rowspan="2">Всего</th>
         </tr>
         <tr>
             <th>До 17 лет</th>
             <th>От 18  до 19 лет</th>
             <th>От 20  до 29 лет</th>
             <th>От 30  до 39 лет</th>
             <th>От 40  до 49 лет</th>
             <th>От 50 лет</th>
         </tr>

     <?
//        damp_array($this->res,1,-1);
        $i=0 ; $itog=array() ;

        ksort($this->res);
        if (_sizeof($this->res)) foreach ($this->res as $group_name=>$recs_pol) {
            $i++;
            for($pol=0;$pol<=1;$pol++){
                ?>
                    <tr>
                        <?if ($pol==0) {?><td rowspan="2"><?echo $i?></td><?}?>
                        <?if ($pol==0) {?><td rowspan="2"><a  target=_blank href="<?echo $this->get_filter_to_params(array(),array('url_report'=>'/cab/reports/report_pp_itog4/'))?>"><?echo $group_name?></a></td><?}?>
                        <td><a  target=_blank href="<?echo $this->get_filter_to_params(array('pol'=>($pol+1)),array('url_report'=>'/cab/reports/report_pp_itog4/'))?>"><?echo $pol?'Женщины':'Мужчины'?></a></td>
                        <?
                            for($j=1;$j<=6;$j++){
                                ?>
                                    <td><?echo $recs_pol[$pol]['e'.$j]; $itog[$group_name][$pol]+=$recs_pol[$pol]['e'.$j]; $itog['e'.$j]+=$recs_pol[$pol]['e'.$j];?></td>
                                <?
                            }
                        ?>
                        <td><?echo $itog[$group_name][$pol]; $itog['all']+=$itog[$group_name][$pol];?></td>
                    </tr>
                <?
            }
        }
        ?>
        <tr class="itog">
            <td colspan="3">ИТОГО</td>
            <?
                for($j=1;$j<=6;$j++){
                    ?>
                        <td><?echo $itog['e'.$j]?></td>
                    <?
                }
            ?>
            <td><?echo $itog['all']?></td>
        </tr>
       </table>
      <?
//    if (!_sizeof($this->arr_mo_to_orgs)) {?><!--<div class="alert" style="text-align:center">Данных по Вашему запросу не найдено</div>--><?//}
  }

  function CSV_report_body($options=array())
  {
    $this->prepare_data($options) ;
//    $i=0 ;  $itog=array() ;
//    if (_sizeof($this->arr_mo_to_orgs)) foreach($this->arr_mo_to_orgs as $org_id=>$mo_count)
//    {     $data=array() ;
//          $data['№']=$i+1 ;
//          $data['Организация']=$this->arr_org_names[$org_id] ;
//          $data['Число МО']=$mo_count ;                                 $itog['mo_count']+=$mo_count ;
//          $sum=array() ;
//          if (_sizeof($this->rules)) foreach($this->rules as $title=>$params)
//             { $rec_work=$this->res[$org_id][$title] ;
//               $data['№']=$i+1 ;
//               $data['Категории АД']=$title ;
//               $data['ЭСМО-допущено']=$rec_work['res1']['e1'] ;         $sum['e1']+=$rec_work['res1']['e1'] ;
//               $data['ЭСМО-не допущено']=$rec_work['res1']['e2'] ;      $sum['e2']+=$rec_work['res1']['e2'] ;
//               $data['РМВ-допущено']=$rec_work['res2']['f1'] ;          $sum['f1']+=$rec_work['res2']['f1'] ;
//               $data['РМВ-не допущено']=$rec_work['res2']['f2'] ;       $sum['f2']+=$rec_work['res2']['f2'] ;
//               $data['Уклонилось']=$rec_work['res2']['f3'] ;            $sum['f3']+=$rec_work['res2']['f3'] ;
//               $data['РМВ+']=$rec_work['res2']['f4'] ;                  $sum['f4']+=$rec_work['res2']['f4'] ;
//               $data['РМВ-']=$rec_work['res2']['f5'] ;                  $sum['f5']+=$rec_work['res2']['f5'] ;
//               $data['процент допущенных']=round((($rec_work['res1']['e1']+$rec_work['res2']['f1']+$rec_work['res2']['f3']+$rec_work['res2']['f4'])/$mo_count*100),1).' %' ;
//               $this->put_data_to_CSV($data,$i) ;
//               $i++ ;
//             }
//          $data['№']=$i+1 ;
//          $data['Категории АД']='ИТОГО' ;
//          $data['ЭСМО-допущено']=$sum['e1'];                            $itog['e1']+=$sum['e1'] ;
//          $data['ЭСМО-не допущено']=$sum['e2'];                         $itog['e2']+=$sum['e2'] ;
//          $data['РМВ-допущено']=$sum['f1'];                             $itog['f1']+=$sum['f1'] ;
//          $data['РМВ-не допущено']=$sum['f2'];                          $itog['f2']+=$sum['f2'] ;
//          $data['Уклонилось']=$sum['f3'];                               $itog['f3']+=$sum['f3'] ;
//          $data['РМВ+']=$sum['f4'];                                     $itog['f4']+=$sum['f4'] ;
//          $data['РМВ-']=$sum['f5'];                                     $itog['f5']+=$sum['f5'] ;
//          $data['процент допущенных']=round((($sum['e1']+$sum['f1']+$sum['f3']+$sum['f4'])/$mo_count*100),1).' %' ;
//          $this->put_data_to_CSV($data,$i) ;
//          $i++ ;
//    }
//
//    $data['№']=$i+1 ;
//    $data['Организация']='ИТОГО' ;
//    $data['Число МО']=$itog['mo_count'] ;
//    $data['Категории АД']='' ;
//    $data['ЭСМО-допущено']=$itog['e1'];
//    $data['ЭСМО-не допущено']=$itog['e2'];
//    $data['РМВ-допущено']=$itog['f1'];
//    $data['РМВ-не допущено']=$itog['f2'];
//    $data['Уклонилось']=$itog['f3'];
//    $data['РМВ+']=$itog['f4'];
//    $data['РМВ-']=$itog['f5'];
//    $data['процент допущенных']=round((($itog['e1']+$itog['f1']+$itog['f3']+$itog['f4'])/$itog['mo_count']*100),1).' %' ;
//    $this->put_data_to_CSV($data,$i) ;

  }

}

?>
