<?php
class report_quiz_section_stats extends c_report
{
    var $title='Результаты контроля знаний - статистика по разделу' ;
    var $personal_id=0 ;
    var $event_id=0 ;
    var $section_id=0 ;
    var $cnt_days=array(0=>'90 дней',1=>'180 дней',2=>'1 год',3=>'все время') ;
    var $usl_time ;
    var $time_from ;
    var $usl_quiz_result ;
    var $rec_section=[] ;



    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='t1.quiz_с_data>='.$this->time_from;
            break ;
            case 1: $this->time_from=mktime(0,0,0,$tt['mon'],$tt['mday']-180,$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'],$tt['year']-1) ;
                $this->usl_time='t1.quiz_с_data>='.$this->time_from;
                break ;
            case 3: $this->usl_time='' ;
                break ;
        }
        if ($this->section_id)
        { $this->filter['theme_id']=$this->section_id  ;
            $this->rec_section=QUIZ()->get_theme_by_id($this->section_id) ;
        }
    }

    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 t2.parent is null' ;
        if ($this->personal_id)    $_usl[]='t1.personal_id='.$this->personal_id ;
        if ($this->event_id)       $_usl[]='t1.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 quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
            else if ($this->section_id)
            {   $childs_sections=TREE('quiz_themes')->get_list_child($this->section_id) ;
                $childs_sections[$this->section_id]=1 ;
                $section_ids=array_keys($childs_sections) ;
            }
            else  $section_ids=array_keys($this->filter['section_ids']) ;

            if (_sizeof($section_ids)) $questions_ids=execSQL_line('select pkey as id from quiz_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_quiz_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 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'] ;

        }
        //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['Тема КЗ']=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 (MEMBER()->setting['personal']['usl_select'])     $info[MEMBER()->setting['personal']['name']]=strip_tags(MEMBER()->setting['personal']['info_filter']);
        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']:'' ;
        // получаем список всех ТЕМ вопросов, которые задавались сотруднику
        // получаем список тем и подтем текущего раздела

        // получаем список разделов текущего и следующего уровня
        $rec_subsections=[] ; $rec_subsections_by_section=[] ;
        $rec_sections=execSQL('select pkey as id,obj_name,clss from quiz_themes where parent='.$this->rec_section['pkey']) ;
        if (_sizeof($rec_sections)) $rec_subsections=execSQL('select pkey as id,obj_name,parent,clss from quiz_themes where parent in ('.implode(',',array_keys($rec_sections)).')') ;


        $level=$this->rec_section['level']+1 ;
        $usl_sections=(_sizeof($rec_sections))? ' and t2.parent'.$level.' in ('.implode(',',array_keys($rec_sections)).')':' and t2.parent'.$level.' in (0)' ;

        $_usl_quiz=[];
        $_usl_quiz[]='not tp.pkey is null' ;
        if ($this->usl_time) $_usl_quiz[]=$this->usl_time ;

        $this->usl_quiz_result=implode(' and ',$_usl_quiz);

        $section_stats=execSQL('select t2.parent'.$level.' as section_id,
                          min(t1.quiz_с_data) as time_from,max(t1.quiz_с_data) as time_to,t1.correct,count(t1.quiz_result_id) as cnt 
                          from view_quiz_result t1 
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.' '.$usl_sections.'   
                          group by t2.parent'.$level.',t1.correct ',0,1) ;
        $section_stats2=group_by_field('section_id',$section_stats,'correct') ;

        $section_learned_stats=execSQL('select t2.parent'.$level.' as section_id,sum(t1.re_ask_result) as sum_correct,count(t1.re_ask_result) as cnt 
                          from view_quiz_learned t1 
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.' '.$usl_sections.'   
                          group by t2.parent'.$level.' ') ;

        $question_stats1=execSQL_row('select parent'.$level.' as section_id,count(pkey)
                            from quiz_questions t2
                            where 1 '.$usl_sections.'   
                            group by parent'.$level) ;

        $level++ ;
        $usl_subsections=(_sizeof($rec_subsections))? ' and t2.parent'.$level.' in ('.implode(',',array_keys($rec_subsections)).')':' and t2.parent'.$level.' in (0)' ;
        $subsections_stats=execSQL('select t2.parent'.$level.' as section_id,
                          t1.correct,min(t1.quiz_с_data) as time_from,max(t1.quiz_с_data) as time_to,count(t1.quiz_result_id) as cnt 
                          from view_quiz_result t1 
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.$usl_subsections.'   
                          group by t2.parent'.$level.',t1.correct ',0,1) ;
        $subsections_stats2=group_by_field('section_id',$subsections_stats,'correct') ;

        $subsections_learned_stats=execSQL('select t2.parent'.$level.' as section_id,sum(t1.re_ask_result) as sum_correct,count(t1.re_ask_result) as cnt 
                          from view_quiz_learned t1 
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                          where '.$this->usl_quiz_result.$usl_sections.'   
                          group by t2.parent'.$level.' ') ;

        $question_stats2=execSQL_row('select parent'.$level.' as section_id,count(pkey)
                            from quiz_questions t2
                            where 1 '.$usl_subsections.'   
                            group by parent'.$level) ;





        //echo 'Статистика по заданным вопросам<br>' ;
        //print_2x_arr($section_stats2);
        //print_2x_arr($subsections_stats2);

        //echo 'Статистика по разделам<br>' ;
        //print_2x_arr($rec_sections);

        //echo 'Статистика по подразделам<br>' ;
        //print_2x_arr($rec_subsections);

        $rec_subsections_by_section=group_by_field('parent',$rec_subsections) ;
        //print_2x_arr($rec_subsections_by_section);


        //damp_array($question_stats2);




        /*?><h2>$rec_sections</h2><?
        print_2x_arr($rec_sections);
        ?><h2>$rec_subsections</h2><?
        print_2x_arr($rec_subsections);
    */

        ?><table class="report_inv basic fz_small full auto"<?echo $id?>>
        <tr><th>ID</th>
            <th>Тема/Раздел</th>
            <th>Дата первого опроса</th>
            <th>Дата последнего опроса</th>
            <th>Число вопросов в теме/разделе</th>
            <th>Число заданных вопросов</th>
            <th style="width:210px;">Процент правильных ответов</th>
            <th>Процент усваиваемости</th>
            <!--<th>Процент покрытия темы/раздела</th>-->
        </tr><?
        if (_sizeof($rec_sections)) foreach($rec_sections as $rec)
        {   $theme_id=$rec['id'] ;
            $stats=$section_stats2[$theme_id] ;
            $cnt_questions_get=$stats[0]['cnt']+$stats[1]['cnt'] ;

            $proc1=($cnt_questions_get)? $stats[1]['cnt']/$cnt_questions_get*100:0 ;
            $proc1=($proc1>=1)? round($proc1):round($proc1,1) ;

            //$proc2=($stats['cnt_questions']*100)? $stats['cnt_questions_get']/$stats['cnt_questions']*100:0 ;
            //$proc2=($proc2>=1)? round($proc2):round($proc2,2) ;

            $proc_learned=($section_learned_stats[$theme_id]['cnt'])? $section_learned_stats[$theme_id]['sum_correct']/$section_learned_stats[$theme_id]['cnt']*100:0 ;
            $proc_learned=($proc_learned>=1)? round($proc_learned):round($proc_learned,1) ;


            ?><tr class=item style="<?if (_sizeof($subsections_stats2)){?>background-color:rgba(0,80,170,0.76);color:white;<?}?>">
            <td class="left"><?echo $rec['id']?></td>
            <td class="left"><?echo $rec['obj_name']?></td>
            <td class="center"><?echo ($stats[0]['time_from'])? date('d.m.Y H:i',$stats[0]['time_from']):''?></td>
            <td class="center"><?echo ($stats[0]['time_to'])? date('d.m.Y H:i',$stats[0]['time_to']):''?></td>
            <td class=""><?echo ($question_stats1[$theme_id])? $question_stats1[$theme_id]:''?></td>
            <td class=""><?echo ($cnt_questions_get)? $cnt_questions_get:''?></td>
            <td class=""><?echo ($proc1)? $proc1.'%':''?></td>
            <td class=""><?echo ($proc_learned)? $proc_learned.'%':''?></td>
            </tr>
            <?
            if (_sizeof($rec_subsections_by_section[$theme_id])) foreach($rec_subsections_by_section[$theme_id] as $rec_subsection)
                //if (_sizeof($stats['section_stats'])) foreach($stats]['section_stats'] as $section_id=>$section_info)
            {   $section_id=$rec_subsection['id'] ;
                $stats=$subsections_stats2[$section_id] ;
                $cnt_questions_get=$stats[0]['cnt']+$stats[1]['cnt'] ;

                $proc1=($cnt_questions_get)? $stats[1]['cnt']/$cnt_questions_get*100:0 ;
                $proc1=($proc1>=1)? round($proc1):round($proc1,1) ;

                $proc_learned=($subsections_learned_stats[$section_id]['cnt'])? $subsections_learned_stats[$section_id]['sum_correct']/$subsections_learned_stats[$section_id]['cnt']*100:0 ;
                $proc_learned=($proc_learned>=1)? round($proc_learned):round($proc_learned,1) ;

                $width=200/100*$proc1 ;
                $bar_color=$this->blend_hex('cc2200','66cc00', $proc1/100);
                $text_color=($proc1>10)? 'white':'black' ;

                $icon='' ;
                switch($rec_subsection['clss'])
                { case 481: $icon='<i class="far fa-bookmark"></i>' ; break ;
                    case 472: $icon='<i class="fas fa-folder-open"></i>' ; break ;

                }


                ?><tr>
                <td class="left"><?echo $rec_subsection['id']?></td>
                <td class="left"><?echo $icon.$rec_subsection['obj_name'].' - '.$rec_subsection['clss']?></td>
                <td class="center"><?echo ($stats[0]['time_from'])? date('d.m.Y H:i',$stats[0]['time_from']):''?></td>
                <td class="center"><?echo ($stats[0]['time_to'])? date('d.m.Y H:i',$stats[0]['time_to']):''?></td>
                <td class=""><?echo ($question_stats2[$section_id])? $question_stats2[$section_id]:''?></td>
                <td><?echo ($cnt_questions_get)? $cnt_questions_get:''?></td>
                <td><?
                    //damp_array($rec_subsection,1,-1);
                    //   damp_array($stats,1,-1);
                    //   echo $section_id;

                    ?>
                    <?echo ($proc1)? $proc1.'%':''?>
                    <!--
                            <div class="bar">
                               <div class="color_bar"><div class="inner" style="background:#<?echo $bar_color?>;width:<?echo $width?>px;color:<?echo $text_color?>;"><?echo $proc1?>%</div></div>
                            </div>-->
                </td>
                <td>
                    <?echo ($proc_learned)? $proc_learned.'%':''?>
                </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);
    }

}

?>
