<?php
class report_poll_stats extends c_report
{
 var $title='Результаты опросов - статистика' ;
 var $personal_id=0 ;
 var $event_id=0 ;
 var $cnt_days=array('1m'=>'1 месяц','3m'=>'3 месяца','6m'=>'16 месяцев','1y'=>'1 год','all'=>'все время') ;
 var $usl_time ;
 var $time_from ;
 var $usl_poll_result ;



 function init($crete_options=array())
 {    $cnt_day=($this->filter['cnt_days'])? (int)$this->filter['cnt_days']:0;
      $tt=getdate() ;
      $this->time_from=0 ;

      switch($cnt_day)
      { case 0: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-90,$tt['year']);
                $this->usl_time='and t1.poll_с_data>='.$this->time_from;
                break ;
        case 1: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-180,$tt['year']);
                $this->usl_time='and t1.poll_с_data>='.$this->time_from;
                break ;
        case 2: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday'],$tt['year']-1) ;
                $this->usl_time='and t1.poll_с_data>='.$this->time_from;
                break ;
        case 3: $this->usl_time='' ;
                break ;
      }
 }

    function setting()
       { list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

         $_usl=array() ;
         $_usl[]='not t3.parent is null' ;
         if ($this->personal_id)    $_usl[]='personal_id='.$this->personal_id ;
         if ($this->event_id)       $_usl[]='event_id='.$this->event_id ;

         $usl_theme_select=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

        if ($this->filter['theme_id'])
        {   $questions_ids=[] ;
            if (!_sizeof($this->filter['section_ids'])) $section_ids=execSQL_line('select pkey as id from poll_themes where parent2='.$this->filter['theme_id'].' ') ;
            else                                       $section_ids=array_keys($this->filter['section_ids']) ;
            if (_sizeof($section_ids)) $questions_ids=execSQL_line('select pkey as id from poll_questions where parent in ('.implode(',',$section_ids).')') ;
            if (_sizeof($questions_ids)) $_usl[]='question_id in ('.implode(',',$questions_ids).')';
        }
        if (_sizeof($this->filter['org_ids']))    $_usl[]='_org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
        if (_sizeof($this->filter['otdel_ids']))  $_usl[]='_otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;

        $this->usl_poll_result=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

         // получаем список всех ТЕМ вопросов, которые задавались сотруднику
         $theme_recs=execSQL('select t4.pkey as theme_id,t4.obj_name as theme_name,
                             t3.pkey as section_id,t3.obj_name as section_name
                             from poll_result t1 
                             left join poll_questions t2 on t2.pkey=t1.question_id 
                             left join poll_themes t3 on t3.pkey=t2.parent 
                             left join poll_themes t4 on t4.pkey=t3.parent2 
                             where '.$usl_theme_select.'   
                             group by t4.pkey,t3.pkey
                             order by t4.indx,t3.indx
                             ',0,1) ;
          $arr_themes=array() ; $arr_themes_section=array() ;
         if (_sizeof($theme_recs)) foreach($theme_recs as $rec)
         {  $arr_themes[$rec['theme_id']]=$rec['theme_name'] ;
            $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;

         }
             //damp_array($arr_themes);

     $this->form_open() ;
     $this->row_open() ;
     $this->fieldset_open() ;
     $this->filter_section_select('theme_id','Тема опроса:',2,$arr_themes) ;
     if ($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы опроса:',4,$arr_themes_section[$this->filter['theme_id']]) ;
     if (!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
     if (!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
     //$this->filter_section_select('view_mode','Обзор:',2,$this->view_mode,array('nospace_element'=>1)) ;
     $this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element')) ;
     $this->row_close() ;
     $this->panel_buttons();
     $this->fieldset_close() ;
     $this->form_close() ;
       }

 function get_arr_info_filters()
 { $info=parent::get_arr_info_filters() ;
   if ($this->filter['time_int'])                        $info['временной интервал']=$this->time_int[$this->filter['time_int']] ;
   if ($this->time_from)                                 $info['Анализ данных']='от '.date('d.m.Y',$this->time_from) ;
   else                                                  $info['Анализ данных']='за все время' ;
   if ($this->filter['theme_id'])                        $info['Тема опроса']=POLL()->get_theme_name_by_id($this->filter['theme_id']);
   if (_sizeof($this->filter['section_ids']))            $info['Раздел опроса']=POLL()->get_theme_name_by_ids(implode(',',array_keys($this->filter['section_ids'])));
   return $info ;
 }



 function get_cnt_items($usl,$options=array()){return(1) ;}

 function get_items($usl,$options=array()){return(array()) ;}

 function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    //$personal_id=($this->personal_id)? $this->personal_id:$this->filter['personal_id'] ;

    // получаем список всех ТЕМ вопросов, которые задавались сотруднику
    $theme_ids=execSQL('select t3.parent as theme_id,min(t1.poll_с_data) as time_from,max(t1.poll_с_data) as time_to,count(distinct(t1.question_id)),t4.obj_name as theme_name 
                        from view_poll_result t1 
                        left join poll_questions t2 on t2.pkey=t1.question_id 
                        left join poll_themes t3 on t3.pkey=t2.parent 
                        left join poll_themes t4 on t4.pkey=t3.parent 
                        where '.$this->usl_poll_result.' '.$this->usl_time.' 
                        group by t3.parent',0,1) ;

    $theme_stats=execSQL('select t3.parent as theme_id,t3.pkey as section_id,count(t1.poll_result_id) as cnt,t3.obj_name as section_name 
                          from view_poll_result t1 
                          left join poll_questions t2 on t2.pkey=t1.question_id
                          left join poll_themes t3 on t3.pkey=t2.parent
                          where '.$this->usl_poll_result.' '.$this->usl_time.'   
                          group by t3.parent,t2.parent ',0,1) ;

    $theme_stats_full=execSQL('select t3.parent as theme_id,t2.parent as section_id,count(t2.pkey) as cnt 
                               from poll_questions t2 
                               left join poll_themes t3 on t3.pkey=t2.parent 
                               group by t3.parent,t2.parent',0,1) ;

    $arr_result=array() ;

    if (_sizeof($theme_stats)) foreach($theme_stats as $rec)
    {  	     $arr_result[$rec['theme_id']]['cnt_questions_get']+=$rec['cnt'] ;
            $arr_result[$rec['theme_id']]['section_stats'][$rec['section_id']]['cnt_questions_get']+=$rec['cnt'] ;
            $arr_result[$rec['theme_id']]['section_stats'][$rec['section_id']]['section_name']=$rec['section_name'] ;
    }
    if (_sizeof($theme_stats_full)) foreach($theme_stats_full as $rec)
    { if (isset($arr_result[$rec['theme_id']])) $arr_result[$rec['theme_id']]['cnt_questions']+=$rec['cnt'] ;
      if (isset($arr_result[$rec['theme_id']]['section_stats'][$rec['section_id']])) $arr_result[$rec['theme_id']]['section_stats'][$rec['section_id']]['cnt_questions']+=$rec['cnt'] ;
    }

    ?><table class="report_inv basic fz_small full auto"<?echo $id?>>
        <tr><th>Тема/Раздел</th><th>Дата первого опроса</th><th>Дата последнего опроса</th><th>Число вопросов в теме/разделе</th><th>Число заданных вопросов</th>
            <!--<th>Процент покрытия темы/раздела</th>-->
            </tr><?
        if (_sizeof($theme_ids)) foreach($theme_ids as $rec)
        {   $theme_id=$rec['theme_id'] ;

            ?><tr class=item style="background-color:rgba(0,80,170,0.76);color:white;">
                <td class="left"><?echo $rec['theme_name']?></td>
                <td class="center"><?echo date('d.m.Y H:i',$rec['time_from'])?></td>
                <td class="center"><?echo date('d.m.Y H:i',$rec['time_to'])?></td>
                <td class=""><?echo $arr_result[$theme_id]['cnt_questions']?></td>
                <td class=""><?echo $arr_result[$theme_id]['cnt_questions_get']?></td>
            </tr>
            <?
            if (_sizeof($arr_result[$theme_id]['section_stats'])) foreach($arr_result[$theme_id]['section_stats'] as $section_id=>$section_info)
                {   ?><tr>
                        <td class="left"><?echo $section_info['section_name']?></td>
                        <td></td>
                        <td></td>
                        <td><?echo $section_info['cnt_questions']?></td>
                        <td><?echo $section_info['cnt_questions_get']?></td>
                    </tr>
                    <?
                }
        }
      ?></table><?
   }


    /**
     * Blend two hexadecimal colours
     * specifying the fractional position.
     *
     * Example:
     *     // 10% along the gradient between #66cc00 and #cc2200
     *     blend_hex('66cc00', 'cc2200', 0.1); // "70bb00"
     */
    function blend_hex($from, $to, $pos = 0.5)
    {
        // 1. Grab RGB from each colour
        list($fr, $fg, $fb) = sscanf($from, '%2x%2x%2x');
        list($tr, $tg, $tb) = sscanf($to, '%2x%2x%2x');

        // 2. Calculate colour based on frational position
        $r = (int) ($fr - (($fr - $tr) * $pos));
        $g = (int) ($fg - (($fg - $tg) * $pos));
        $b = (int) ($fb - (($fb - $tb) * $pos));

        // 3. Format to 6-char HEX colour string
        return sprintf('%02x%02x%02x', $r, $g, $b);
    }

}

?>
