<?php
class report_quiz_question_rating extends c_report
{
    var $title='Контроль знаний - рейтинг вопросов' ;
    var $cnt_days=array(0=>'30 дней',1=>'90 дней',2=>'180 дней',3=>'1 год',4=>'все время') ;
    var $question_order=array(0=>'Худшие',1=>'Лучшие') ;
    var $usl_time ;
    var $section_id=0 ;
    var $time_from ;
    var $usl_quiz_result ;
    var $rec_section=[] ;
    var $view_by_space_filter=1;
    var $view_type = 'section';
    var $min_cnt=1;
    var $min_limit=20;
    var $view_count=0;

    var $settings_name=['question_count'=>'Число заданных вопросов от:'];
    var $sql_variable=['main_table'=>'view_quiz_result','correct_column_name'=>'correct'];
    var $table_column_name=['cnt'=>'Число заданных вопросов','perc'=>'Процент правильных ответов'];

    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']-29,$tt['year']);
                $this->usl_time='t1.quiz_с_data>='.$this->time_from;
                break ;
            case 1: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-89,$tt['year']);
                $this->usl_time='t1.quiz_с_data>='.$this->time_from;
                break ;
            case 2: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-179,$tt['year']);
                $this->usl_time='t1.quiz_с_data>='.$this->time_from;
                break ;
            case 3: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday'],$tt['year']-1) ;
                $this->usl_time='t1.quiz_с_data>='.$this->time_from;
                break ;
            case 4: $this->usl_time='' ;
                break ;
        }

        if (!is_numeric($this->filter['question_limit']) or !$this->filter['question_limit']) $this->filter['question_limit']=$this->min_limit;;

        if (!$this->filter['question_count']) $this->filter['question_count']=$this->min_cnt;

        if ($this->section_id) {
            $this->filter['theme_id']=$this->section_id  ;
            $this->rec_section=QUIZ()->get_theme_by_id($this->section_id) ;

            $child_section_cnt=execSQL_value('select count(pkey) from quiz_themes where parent='.$this->rec_section['pkey']);
            if ($child_section_cnt==0) $this->view_type='question';
        }

        $_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 ;

        if ($this->filter['theme_id'])
        {   $questions_ids=[] ; $section_ids=[];
            if (!$this->filter['section_id']) $section_ids=execSQL_line('select pkey as id from quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
            else {
                $section_level=execSQL_value('select level from quiz_themes where pkey='.$this->filter['section_id']);
                if ($section_level) {
                    $section_ids=execSQL_line('select pkey as id from quiz_themes where parent'.$section_level.'='.$this->filter['section_id'].' ') ;
                    if (!_sizeof($section_ids)) $section_ids=[$this->filter['section_id']];
                }
            }
            if (_sizeof($section_ids))  {
                $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent in ('.implode(',',$section_ids).')') ;
            } else {
                $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent='.$this->filter['theme_id']) ;
            }
            if (_sizeof($questions_ids)) $_usl[]='question_id in ('.implode(',',$questions_ids).')';
            else $_usl[]='question_id=-1';
        }
        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'])).')' ;
        if (_sizeof($this->filter['working_ids']))  $_usl[]='t1.working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;

        if ($this->filter['view_count']) $this->view_count=1;

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

    function setting()
    {
        if (!$this->personal_id) {
            list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;
        } else {
            $arr_orgs_ids=[]; $arr_otdel_ids=[]; $arr_works_ids=[];
        }

        $_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' ;
//
//        $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 quiz_result t1
//                             left join quiz_questions t2 on t2.pkey=t1.question_id
//                             left join quiz_themes t3 on t3.pkey=t2.parent
//                             left join quiz_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'] ;
//        }

        $parent_themes = execSQL('select t3.pkey,t3.parent,t3.parent2,t3.level,t3.obj_name 
                             from quiz_result t1 
                                        inner join quiz_questions t2 on t2.pkey=t1.question_id 
                                        inner join quiz_themes t3 on t3.pkey=t2.parent
                             where '.$usl_theme_select.'   
                                        group by t3.pkey
                                        order by t3.pkey
        ');

        $themes=execSQL('select pkey,clss,obj_name,parent,level,parent2 from quiz_themes where level>0 order by level,parent');

        $themes=$this->hierarchy_array($themes);


        $max_level=0;
        foreach ($themes as $key=>&$theme) {
            if ($theme['level']>$max_level) $max_level=$theme['level'];
            if (_sizeof($parent_themes[$key])) { $theme['in_view']=true;}
        }

        if ($max_level>0) {
            for ($i=$max_level;$i>0;$i--) {
                foreach ($themes as $key=>$theme) {
                    if ($theme['level']!=$i) continue;
                    if (!$theme['in_view']) {
                        unset($themes[$key]);
                        continue;
                    }
                    if ($theme['parent']) {
                        $themes[$theme['parent']]['in_view']=true;
                    }
                    if ($theme['clss']==481) unset($themes[$key]);
                }
            }
        }

        $arr_themes=array() ; $arr_themes_section=array() ;

        foreach ($themes as $key=>$theme) {
            if ($theme['level']==2) {
                $arr_themes[$key]=$theme['obj_name'] ;
//                $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;
            } elseif ($theme['level']>2) {
                $arr_themes_section[$theme['parent2']][$key]=$this->empty_space($theme['level']).$theme['obj_name'] ;
            }
        }

        $this->form_open() ;
        $this->fieldset_open() ;
        $this->row_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->filter['theme_id']) $this->filter_section_select('section_id','Раздел КЗ:',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) ;
            if (!$this->personal_id) $this->filter_section_select_multiple('working_ids','Должность:',2,$arr_works_ids) ;
            $this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element'=>1)) ;
        $this->row_close() ;
        $this->row_open() ;
            $this->filter_section_select('question_order','Сортировка:',2,$this->question_order,array('nospace_element'=>1)) ;
            $this->filter_section_input_text('question_count',$this->settings_name['question_count'],2) ;
            $this->filter_section_input_text('question_limit','Отображать:',2) ;
//            $this->filter_section_select('view_count','Отображать кол-во вопросов:',2,$this->question_order,array('nospace_element'=>1)) ;
        $this->row_close() ;
        $this->row_open() ;
            ?>
            <section class="col col-2">
                <label class="checkbox">
                    <input type="checkbox" name="filter[view_count]" value="1" <?if ($this->filter['view_count']) echo 'checked'?>><i></i>Отображать кол-во вопросов
                </label>
            </section>
            <?
        $this->row_close() ;
        $this->panel_buttons();
        $this->fieldset_close() ;
        $this->form_close() ;
    }

    function min_setting()
    {
        $this->form_open() ;
        $this->fieldset_open() ;
        $this->row_open() ;
        $this->filter_section_select('question_order','Сортировка:',2,$this->question_order,array('nospace_element'=>1)) ;
        $this->filter_section_input_text('question_count',$this->settings_name['question_count'],2) ;
        $this->filter_section_input_text('question_limit','Отображать:',2) ;
        $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['Тема КЗ']=QUIZ()->get_theme_name_by_id($this->filter['theme_id']);
//        if (_sizeof($this->filter['section_ids']))             $info['Раздел КЗ']=QUIZ()->get_theme_name_by_ids(implode(',',array_keys($this->filter['section_ids'])));
        if ($this->filter['section_id'])                      $info['Раздел КЗ']=QUIZ()->get_theme_name_by_id($this->filter['section_id']);
        return $info ;
    }



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

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

    function print_template_HTML()
    {

        $data = $this->prepare_data();

        $this->table_view_panel($data);

    }

    function prepare_data()
    {
        $order = '';
        if ($this->filter['question_order']==1) $order='desc';

        if (MEMBER()->personal_viewer_name) $usl_str='and t1.personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;

        $having='';
        if (is_numeric($this->filter['question_count']) and $this->filter['question_count']>0) $having=' having cnt>='.$this->filter['question_count'];

        $usl_time='';
        if ($this->usl_quiz_result) $usl_time='and '.$this->usl_time;

        $recs = execSQL('select t4.question_id,t4.sum_correct,t4.cnt,round((sum_correct/t4.cnt * 100 ),2) as perc,t4.obj_name
                               from (select t1.question_id,sum(t1.'.$this->sql_variable['correct_column_name'].') as sum_correct,count(t1.quiz_result_id) as cnt,t2.obj_name 
                                    from '.$this->sql_variable['main_table'].' t1 
                                      left join quiz_questions t2 on t2.pkey=t1.question_id
                                      left join quiz_themes t3 on t3.pkey=t2.parent
                                      left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                                      where '.$this->usl_quiz_result.' '.$usl_time.' and not tp.pkey is null 
                                      group by t1.question_id
                                        '.$having.'
                               ) t4
                           order by perc '.$order.'
                           limit '.$this->filter['question_limit'].'
        ');

        return $recs;
    }

    function table_view_panel($data=[],$options=[])
    {
        $table_class='basic auto fz_small';
        if (!$options['half_view_HTML']) $table_class=$table_class.' full';
        if ($this->filter['question_order']) {
            $icon='<i class="fa fa-thumbs-up icon_best" title="Топ '.$this->filter['question_limit'].' лучших"></i>';
        } else {
            $icon='<i class="fa fa-thumbs-down icon_worst" title="Топ '.$this->filter['question_limit'].' худших"></i>';
        }
        if (_sizeof($data)) {
            ?>
            <table class="<?=$table_class?>">
                <tr>
                    <th style="width: 20px"><?=$icon?></th>
                    <th>Вопрос</th>
                    <?if ($this->view_count) {?><th style="width: 20px"><?=$this->table_column_name['cnt']?></th><?}?>
                    <th style="width: 20px"><?=$this->table_column_name['perc']?></th>
                </tr>
                <?
                foreach ($data as $stats) {
                    ?>
                    <tr>
                        <td><?echo ++$i?></td>
                        <td class="left"><a class="new_window" href="/window/quiz/question/card/<?=$stats['question_id']?>/"><?=$stats['obj_name']?></a></td>
                        <?if ($this->view_count) {?><td><?=$stats['cnt']?></td><?}?>
                        <td><?=$stats['perc']?></td>
                    </tr>
                    <?
                }
                ?>
            </table>
            <?
        }
    }

    function half_view_HTML($options=[])
    {

        $data = $this->prepare_data();

        $this->table_view_panel($data,['half_view_HTML'=>1]);

    }

    function hierarchy_array($arr,$prev_parent=0) {
        $temp_arr=[];
        foreach ($arr as $key=>$value) {
            if ($value['parent']==$prev_parent) {
                $temp_arr[$key]=$value;
                $temp_arr2=$this->hierarchy_array($arr,$value['pkey']);
                if (_sizeof($temp_arr2)) $this->merge_arr($temp_arr,$temp_arr2);
            }
        }
        return $temp_arr;
    }

    function merge_arr(&$arr1,$arr2)
    {
        if (_sizeof($arr1)) {
            foreach ($arr2 as $key=>$value) {
                $arr1[$key]=$value;
            }
        } else {
            $arr1=$arr2;
        }

    }

    function empty_space($level) {
        $min=4;
        $result='';
        if ($level>=$min) {
            for ($i=$min;$i<=$level;$i++) {
                $result.='&nbsp;&nbsp;&nbsp;';
            }
        }
        return $result;
    }

}

?>
