<?php
include_once('c_poll_question_card.php');
class c_page_cab_poll_question_card_orgs extends c_page_cab_poll_question_card
{
    public $h1='Опросы - карточка вопроса - статистика по подразделениям';
    public $rec_question ;

    function block_main()
    {
        $this->page_title() ;
        $this->setting() ;
        $this->report_stats() ;

    }

   function setting($options=array())
   {

      $this->form_open() ;

      if (!$this->personal_id)
      { $this->row_open() ;

        list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter,['filter_reffer'=>$this->rec_event['_reffer']]) ;

        $this->filter_section_select_multiple('org_ids','Организация:',4,$arr_orgs_ids) ;
        $this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids) ;
        //$this->filter_section_select_multiple('working_ids','Должность:',2,$arr_works_ids) ;
        $this->row_close() ;
      }

      //$this->row_open() ;
      //$this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
      //$this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;

      //$this->row_close() ;
      $this->panel_buttons() ;
      $this->form_close() ;

    }

    function report_stats($options=array())
    { $view_level=3 ;

      $_usl=[] ;
      $_usl[]='t1.question_id='.$this->rec_question['pkey'] ;
      $_usl[]='t1._org_id>0' ;
      $_usl[]='not MPS.pkey is null' ;

        //$_usl[]='t1.parent'.$this->rec_section['level'].'='.$this->rec_section['pkey'] ; // все вопросы в текущем разделе

        if (_sizeof($this->filter['org_ids']))
        {  $level_info=execSQL_row('select pkey,level from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['org_ids'])).')') ;
            $_usl_org=[] ;
            if (_sizeof($level_info))
            { foreach($level_info as $id=>$level) $_usl_org[]='so.parent'.$level.'='.$id ;
              $_usl[]='('.implode(' or ',$_usl_org).')' ;
            }
        }
        if (_sizeof($this->filter['otdel_ids']))
        {  $level_info=execSQL_row('select pkey,level from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['otdel_ids'])).')') ;
            $_usl_org=[] ;
            if (_sizeof($level_info))
            { foreach($level_info as $id=>$level) $_usl_org[]='so.parent'.$level.'='.$id ;
              $_usl[]='('.implode(' or ',$_usl_org).')' ;
            }
            $max_otdel_level=max($level_info) ;
            //echo '$max_otdel_level='.$max_otdel_level.'<br>' ;
            if ($max_otdel_level>$view_level) $view_level=$max_otdel_level ;
        }

       $group_fname='parent'.$view_level ;
      //echo '$group_fname='.$group_fname.'<br>' ;
      $_usl[]='t1.'.$group_fname.'>0' ;

      $usl_select=implode(' and ',$_usl) ;


      //damp_array($this->filter);
      if ($this->rec_question['answer_type']==2)
      // запрос под вопросы
      $stats=execSQL('select t1.'.$group_fname.' as dep_id,t1.answer_id,count(distinct(t1.personal_id)) as cnt 
                      from view_poll_result t1
                      left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.personal_id
                      left join obj_site_personals so on so.pkey=t1.personal_id
                      where '.$usl_select.' 
                      group by t1.'.$group_fname.',t1.answer_id 
                      order by t1.'.$group_fname.',t1.answer_id 
                      ',0,1) ;
      // запрос под баллы
      else $stats=execSQL('select t1.'.$group_fname.' as dep_id,t1.answer_ball as answer_id,
                      count(distinct(t1.personal_id)) as cnt 
                      from view_poll_result t1
                      left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.personal_id
                      left join obj_site_personals so on so.pkey=t1.personal_id
                      where '.$usl_select.' 
                      group by t1.'.$group_fname.',t1.answer_ball 
                      order by t1.'.$group_fname.',t1.answer_ball 
                      ',0,1) ;

      $rec_stats2=[] ;
      if (_sizeof($stats)) foreach($stats as $rec_stat) $rec_stats2[$rec_stat['dep_id']][$rec_stat['answer_id']]=$rec_stat['cnt'] ;
      //$arr=group_by_field('dep_id',$stats,'answer_id') ;
      //damp_array($rec_stats2);
      if (!sizeof($rec_stats2)){ echo '<div class=alert>Недостаточно данных для показа отчета</div>'; return ;}

      if ($this->rec_question['answer_type']==2)
       { $arr_answers=execSQL_row('select pkey,obj_name from poll_answers where question_id='.$this->rec_question['pkey']) ;
         $arr_answers[0]='Уклонились от ответа' ;
       }
      else $arr_answers=[1=>'1 балл',2=>'2 балла',3=>'3 балла',4=>'4 балла',5=>'5 баллов',0=>'Уклонились от ответа'] ;


      $arr_org_otdels=TREE('obj_site_personals')->get_list_strukture('clss in (1,207,208)');

      $stats_cnt_all=execSQL_row('select t1.'.$group_fname.' as dep_id,count(t1.pkey) as cnt
                                  from obj_site_personals t1
                                  left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=t1.pkey
                                  where t1.enabled=1 and t1.'.$group_fname.'>0 and t1.'.$group_fname.' in ('.implode(',',array_keys($rec_stats2)).') and not MPS.pkey is null
                                  group by t1.'.$group_fname.'
      ') ;


    if ($this->rec_question['is_second']==0)
    {
     $stats_cnt_poll=execSQL_row('select so.'.$group_fname.' as dep_id,count(distinct(res.personal_id)) as cnt
                                  from poll_result res 
                                  left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=res.personal_id
                                  left join obj_site_personals so on so.pkey=res.personal_id
                                  where res.question_id='.$this->rec_question['pkey'].' 
                                  and so.enabled=1 and so.'.$group_fname.'>0 
                                  and so.'.$group_fname.' in ('.implode(',',array_keys($rec_stats2)).') 
                                  and not MPS.pkey is null
                                  and res.personal_id>0
                                  group by so.'.$group_fname.'
                                 ') ;
    }
    else
    {
      $parent_question=$this->rec_question['parent'.($this->rec_question['level']-2)] ;
      $parent_answer=$this->rec_question['parent'.($this->rec_question['level']-1)] ;



      $stats_cnt_poll=execSQL_row('select so.'.$group_fname.' as dep_id,count((r.personal_id)) as cnt
                                   from poll_result r 
                                   left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=r.personal_id
                                   left join obj_site_personals so on so.pkey=r.personal_id
                                   where r.question_id='.$parent_question.' and so.enabled=1 and so.'.$group_fname.'>0
                                   and so.'.$group_fname.' in ('.implode(',',array_keys($rec_stats2)).') 
                                   and not MPS.pkey is null
                                   and not r.pkey is null
                                   and s.personal_id>0
                                   group by so.'.$group_fname.'
                                  ') ;


    }



      //damp_array($arr_org_otdels);

      $id=($options['id'])? 'id='.$options['id']:'' ;
      ?><table class="basic fz_small full auto"<?echo $id?>>
          <tr><th rowspan=2 style="text-align:left;">Организация/подразделение:</th>
              <th rowspan=2 >Всего сотрудников</th>
              <th rowspan=2 >Получили вопрос</th>
              <th rowspan=2 >Процент охвата</th>
              <th colspan=<?echo _sizeof($arr_answers)?>>Ответы</th>
          </tr>
          <tr>
              <?if (_sizeof($arr_answers)) foreach($arr_answers as $answer_id=>$text){?><th><?echo $text?></th><?}?>
          </tr><?
            if (_sizeof($arr_org_otdels)) foreach($arr_org_otdels as $dep_id=>$dep_name) if (isset($rec_stats2[$dep_id]))
            {
                $k1=($stats_cnt_all[$dep_id])? round($stats_cnt_poll[$dep_id]/$stats_cnt_all[$dep_id]*100):0 ;

                ?><tr class="item">
                    <td class="left"><?echo str_replace('Персонал компании / ','',$dep_name)?> [<?echo $dep_id?>]</td>
                    <td><?echo ($stats_cnt_all[$dep_id])? $stats_cnt_all[$dep_id]:'-'?></td>
                    <td><?  $url='/frame/poll/question/card/'.$this->rec_question['pkey'].'/stats/[dep_id='.$dep_id.']/' ;
                            echo ($stats_cnt_poll[$dep_id])? '<a href="'.$url.'">'.$stats_cnt_poll[$dep_id].'</a>':'-'?></td>
                    <td><?echo ($k1)? $k1.'%':'-'?></td>
                    <? $cnt_org=0 ;
                       if (_sizeof($arr_answers)) foreach($arr_answers as $answer_id=>$text)
                        { $answer_id2=($answer_id>0)? $answer_id:-1 ;
                          if ($this->rec_question['answer_type']==2) $url='/frame/poll/question/card/'.$this->rec_question['pkey'].'/stats/[dep_id='.$dep_id.',answer_ids=('.$answer_id2.')]/' ;
                          else $url='/frame/poll/question/card/'.$this->rec_question['pkey'].'/stats/[dep_id='.$dep_id.',answer_balls=('.$answer_id2.')]/' ;
                          ?><td><?echo ($rec_stats2[$dep_id][$answer_id])? '<a href="'.$url.'">'.$rec_stats2[$dep_id][$answer_id].'</a>':'-'?></td><?
                          if ($rec_stats2[$dep_id][$answer_id]) $cnt_org+=$rec_stats2[$dep_id][$answer_id] ;
                        }
                    ?>
                </tr><?
            }
        ?></table><?
        //damp_array($rec) ;

      /*
          $stats_cnt_poll=execSQL('select s.*,sq.pkey as sq_pkey,sq.question_id
                                       from poll_sessions_questions sq
                                       left join poll_sessions s on s.pkey=sq.parent
                                       left join '.MEMBER()->personal_viewer_name.' MPS on MPS.pkey=s.personal_id
                                       left join obj_site_workers so on so.personal_id=s.personal_id
                                       where so.enabled=1 and so.parent3>0 and so.parent3=20421 and not MPS.pkey is null


           ',2,1) ;
      */
    }





}

?>
