<?php
include_once(_DIR_EXT.'/aspmo_pp/i_source.php') ;
class report_pp_itog2 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="select">
                                  <select name="filter[tk]"><option value="0">Все</option><?
                                    if (_sizeof($_SESSION['ARR_mo_tk_type'])) foreach($_SESSION['ARR_mo_tk_type'] as $id=>$name) {?><option value="<?echo $id+1?>" <?if($this->filter['tk']==($id+1)) 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>
                      </div>
                      <div class="row">
                          <section class="col col-6">
                              <label class="label">Должность</label>
                              <? // если определены временные рамки - показывам делаем выборку по должностям, которые есть в этих рамках
                                                                      if (isset($this->filter['data_from']) and $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']) ;
                                                                          $works_ids=execSQL_row('select distinct(working),1 from '.ESMO()->view_mo_session.' where c_data>='.strtotime($this->filter['data_from']).' and c_data<='.$time_to) ;
                                                                      }
                              ?>

                              <label class="select">
                                  <select name="filter[working][]" class="js-basic-multiple js-states form-control" multiple="multiple"><option></option>
                                     <?
                                         foreach(_IL('IL_works')->recs as $rec) if (!_sizeof($works_ids) or isset($works_ids[$rec['id']])) {?><option value="<?echo $rec['id']?>" <?if (isset($this->filter['working'][$rec['id']])) echo 'selected'?>><?echo $rec['obj_name']?></option><?}

                                      ?>
                                  </select>
                              </label>
                          </section>
                          <section class="col col-2">
                               <label class="label">Возраст от:</label>
                               <label class="input"><input type="text" name="filter[age_from]" value="<?echo $this->filter['age_from']?>"></label>
                           </section>
                           <section class="col col-2">
                               <label class="label">Возраст до:</label>
                               <label class="input"><input type="text" name="filter[age_to]" value="<?echo $this->filter['age_to']?>"></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 (_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() ;
    $this->rules[0]            =array('result'=>'ok') ;
    $this->rules[1]            =array('result'=>'Зрачки сужены');
    $this->rules[2]            =array('result'=>'Зрачки расширены (мидриаз)');
    $this->rules[3]            =array('result'=>'реакция отсутствует');
    $this->rules[4]            =array('result'=>'Недостаточный процент распознания');
    $this->rules[5]            =array('result'=>'реакция ослаблена');
    $this->rules[6]            =array('result'=>'false');

    $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 (_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,_pp_result,group_id,parent,personal_parent,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)
    {  $org_id=0 ;
       if ($this->filter['dep_id']) $org_id=$rec_mo['personal_parent'.($cur_level+1)] ;
       if (!$org_id) $org_id=$rec_mo['personal_parent'.$cur_level] ;
       if (!$org_id) $org_id=$rec_mo['personal_parent2'] ;
       if (!$org_id) $org_id=$rec_mo['personal_parent'] ;
//       if (!$org_id) $org_id=$rec_mo['parent'] ;
       $work_id=$rec_mo['working'] ;
       $cnt_rules=0 ;
       $ok=0 ;
       // пропускаем МО через правила
       if (_sizeof($this->rules)) foreach($this->rules as $title=>$params)
       {   // если попали в правило
           if (!$rec_mo['_pp_result']) $rec_mo['_pp_result']='false' ;
           if ($rec_mo['_pp_result']==$params['result'])
           {   // Результат на ЭСМО
               $m=$rec_mo['model'] ; //$ok=0 ;
               if ($m==1 or $m==3)                                      { $this->res[$org_id][$rec_mo['group_id']][$title]['res1']['e1']++ ; $ok=1 ; }
               if ($m==2 or $m==4 or $m==5 or $m==6 or $m==7 or $m==8)  { $this->res[$org_id][$rec_mo['group_id']][$title]['res1']['e2']++ ; $ok=1 ; }
               // Результат после прохождения врача
               if ($m==5 or $m==7)                                      { $this->res[$org_id][$rec_mo['group_id']][$title]['res2']['f1']++ ; $ok=1 ; }
               if ($m==6 or $m==8)                                      { $this->res[$org_id][$rec_mo['group_id']][$title]['res2']['f2']++ ; $ok=1 ; }
               if ($m==2 or $m==4)                                      { $this->res[$org_id][$rec_mo['group_id']][$title]['res2']['f3']++ ; $ok=1 ; }
               if ($m==9)                                               { $this->res[$org_id][$rec_mo['group_id']][$title]['res2']['f4']++ ; $ok=1 ; }
               if ($m==10)                                              { $this->res[$org_id][$rec_mo['group_id']][$title]['res2']['f5']++ ; $ok=1 ; }

               //
               $cnt_rules++ ;
               //$arr_mo[]=$rec_mo ;
               //$flag=1 ;
           }
       }

      if ($ok or 1)
      {
           // количество МО работников
           $this->arr_mo_to_orgs[$org_id][$rec_mo['group_id']]++ ;
           // название организации
           if ($org_id) $this->arr_org_names[$org_id]=PERSONAL()->get_name_by_id($org_id) ; //$rec_mo['_org_name'] ;
           //категория сотрудников
           $arr_work_names[$work_id]=_IL('IL_works')->recs[$rec_mo['working']]['obj_name'] ; // $rec_member['_work_name'] ;

      } // else $recs_after[]=$rec_mo ;

    }
}

function HTML_report_body($options=array())
{

    $this->prepare_data($options) ;
    $arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206');

    ?><table class="basic fz_small full auto">
         <tr><th rowspan="2">№</th>
             <th rowspan="2">Место работы</th>
             <th rowspan="2">Группа</th>
             <th rowspan="2">Кол-во МО</th>
             <th rowspan="2">Категории<br>пупиллометрии</th>
             <th colspan="2">Результат на ЭСМО</th>
             <th colspan="5">Результат после прохождения врача</th>
             <th rowspan="2">% допущенных</th>
         </tr>
         <tr><th>Допущено<div class="comment small"><span class="nowrap">МО1+</span>&nbsp;&nbsp;
                                                    <span class="nowrap">МО2+</span>&nbsp;&nbsp;
                         </div>
             </th>
             <th>Не допущено<div class="comment small"><span class="nowrap">МО1-</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-МО2-</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-МО2-РМВ+</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-МО2-РМВ-</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-РМВ+</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-РМВ-</span>
                            </div>
             </th>
             <th>Допущено<div class="comment small"><span class="nowrap">МО1-МО2-РМВ+</span>&nbsp;&nbsp;
                                                    <span class="nowrap">МО1-РМВ+</span>&nbsp;&nbsp;
                         </div>
             </th>
             <th>Не допущено<div class="comment small"><span class="nowrap">МО1-МО2-РМВ-</span>&nbsp;&nbsp;
                                                       <span class="nowrap">МО1-РМВ-</span>&nbsp;&nbsp;
                            </div>
             </th>
             <th>Уклонилось<div class="comment small"><span class="nowrap">МО1-</span>&nbsp;&nbsp;
                                                      <span class="nowrap">МО1-МО2-</span>&nbsp;&nbsp;
                           </div>
             </th>
             <th><span class="nowrap">РМВ+</span></th>
             <th><span class="nowrap">РМВ-</span></th>
         </tr>
     <? //damp_array($this->arr_mo_to_orgs,1,-1);
        $i=0 ; $itog=array() ;
        if (_sizeof($this->arr_mo_to_orgs)) foreach($this->arr_mo_to_orgs as $org_id=>$recs_mo_to_orgs_group)
         {   $i++ ;
             $group_cnt=count($this->res[$org_id]);
             ?><tr><td rowspan="<?echo _sizeof($this->rules)*$group_cnt+$group_cnt+1?>"><?echo $i?></td>
                 <td class="left" rowspan="<?echo _sizeof($this->rules)*$group_cnt+$group_cnt+1?>">
                     <? //if (!$org_id) $org_id=1 ;

                        $childs_orgs_cnt=execSQL_value('select count(pkey) from obj_site_personals where parent='.$org_id.' and enabled=1 and clss in (207,208)') ;
                        if ($childs_orgs_cnt){?><a  target=_blank href="<?echo $this->get_filter_to_params(array('dep_id'=>$org_id),array('url_report'=>'/cab/reports/report_pp_itog3/'))?>"><?echo $this->arr_org_names[$org_id]?></a><?}
                        else echo $this->arr_org_names[$org_id] ;
                     ?>
                 </td>
                 <? foreach ($this->res[$org_id] as $group_id=>$value) {
                    $mo_count=$recs_mo_to_orgs_group[$group_id];
                    ?><tr><?
                    ?>
                     <td rowspan="<?echo _sizeof($this->rules)+1?>"><a  target=_blank href="<?echo $this->get_filter_to_params(array('dep_id'=>$org_id,'group_id'=>$group_id),array('url_report'=>'/cab/reports/report_pp_itog3/'))?>"><?echo $arr_groups[$group_id]?></a></td>
                     <td rowspan="<?echo _sizeof($this->rules)+1?>"><a  target=_blank href="<?echo $this->get_filter_to_params(array('dep_id'=>$org_id,'group_id'=>$group_id),array('url_report'=>'/cab/reports/report_pp_itog3/'))?>"><?echo $mo_count ; $itog['mo_count']+=$mo_count ; ?></a></td>
                     <?  $sum=array() ; $line=0 ;
                         if (_sizeof($this->rules)) foreach($this->rules as $title_id=>$params)
                         { if ($line) echo '<tr>' ;
                           $rec_work=$this->res[$org_id][$group_id][$title_id] ;
                           ?><td class="left"><a  target=_blank href="<?echo $this->get_filter_to_params(array('dep_id'=>$org_id,'group_id'=>$group_id,'pp_result'=>$title_id+1),array('url_report'=>'/cab/reports/report_pp_itog3/'))?>"><? echo $GLOBALS['pp_result'][$title_id] ;?></a></td>
                             <?
                                 for($j=1;$j<=2;$j++){
                                     ?>
                                     <td><? if ($rec_work['res1']['e'.$j]) echo $rec_work['res1']['e'.$j] ; $sum['e'.$j]+=$rec_work['res1']['e'.$j] ; ?></td>
                                     <?
                                 }
                             ?>
                             <?
                                 for($j=1;$j<=5;$j++){
                                     ?>
                                     <td><? if ($rec_work['res2']['f'.$j]) echo $rec_work['res2']['f'.$j] ; $sum['f'.$j]+=$rec_work['res2']['f'.$j] ; ?></td>
                                     <?
                                 }
                             ?>
                             <td><? echo round((($rec_work['res1']['e1']+$rec_work['res2']['f1']+$rec_work['res2']['f4'])/$mo_count*100),1).' %' ; ?></td>
                            </tr>
                           <?
                           $line++ ;
                         }
                        ?><tr class="subitog">
                          <td class="left">ИТОГО</td>
                          <td><? if ($sum['e1']) echo $sum['e1'] ; $itog['e1']+=$sum['e1'] ; ?></td>
                          <td><? if ($sum['e2']) echo $sum['e2'] ; $itog['e2']+=$sum['e2'] ; ?></td>
                          <td><? if ($sum['f1']) echo $sum['f1'] ; $itog['f1']+=$sum['f1'] ; ?></td>
                          <td><? if ($sum['f2']) echo $sum['f2'] ; $itog['f2']+=$sum['f2'] ; ?></td>
                          <td><? if ($sum['f3']) echo $sum['f3'] ; $itog['f3']+=$sum['f3'] ; ?></td>
                          <td><? if ($sum['f4']) echo $sum['f4'] ; $itog['f4']+=$sum['f4'] ; ?></td>
                          <td><? if ($sum['f5']) echo $sum['f5'] ; $itog['f5']+=$sum['f5'] ; ?></td>
                          <td><? echo round((($sum['e1']+$sum['f1']+$sum['f4'])/$mo_count*100),1).' %' ; ?></td>
<!--                          <td>--><?// echo round((($sum['e1']+$sum['f1']+$sum['f3']+$sum['f4'])/$mo_count*100),1).' %' ; ?><!--</td>-->
                          </tr>
                 </tr>
                        <?
                 }

                 ?>
           <?
         }
         if (_sizeof($this->arr_mo_to_orgs))
         {?><tr class="itog">
             <td></td>
             <td>ИТОГО</td>
             <td></td>
             <td><?echo $itog['mo_count']?></td>
             <td></td>
             <td><?if ($itog['e1']) echo $itog['e1']?></td>
             <td><?if ($itog['e2']) echo $itog['e2']?></td>
             <td><?if ($itog['f1']) echo $itog['f1']?></td>
             <td><?if ($itog['f2']) echo $itog['f2']?></td>
             <td><?if ($itog['f3']) echo $itog['f3']?></td>
             <td><?if ($itog['f4']) echo $itog['f4']?></td>
             <td><?if ($itog['f5']) echo $itog['f5']?></td>
<!--             <td>--><?// echo round((($itog['e1']+$itog['f1']+$itog['f3']+$itog['f4'])/$itog['mo_count']*100),1).' %' ; ?><!--</td>-->
             <td><? echo round((($itog['e1']+$itog['f1']+$itog['f4'])/$itog['mo_count']*100),1).' %' ; ?></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) ;
//
//  }

}

?>
