<?php
include_once(_DIR_EXT.'/quiz/report_quiz_persons_rating.php') ;
class report_quiz_personal_rating_graf extends report_quiz_persons_rating
{
    var $title='Результаты контроля знаний - рейтинг сотрудника (график)' ;
    var $personal_id=0 ;
    var $personal_rec=0 ;
    var $event_id=0 ;
    var $cnt_days=array(0=>'1 год',1=>'все время',2=>'90 дней',3=>'180 дней') ;
    var $usl_time ;
    var $time_from=0 ;
    var $time_to ;
    var $usl_quiz_result ;
    var $use_fusioncharts=1;
    var $min_questions_get=10;
    var $show_learned_stats=0;
    var $show_quiz_theme_stats=0;
    var $debugs=[];
    var $arr_orgs_ids;
    var $arr_otdel_ids;
    var $arr_works_ids;
    var $arr_themes;
    var $recs_persons_types;
    var $debug=0;
    var $table_quiz_person_rating;

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

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

        // если выбрана тема или раздел - показывать статистику по охвату тему
        if ($this->filter['theme_id'] or _sizeof($this->filter['section_ids'])) $this->show_quiz_theme_stats=1 ;

        //if ($_GET['debug']) $this->debug=$_GET['debug'] ;
    }

    function setting()
    {
        $this->prepare_setting_arr();

        $this->form_open();
        $this->row_open();
        $this->fieldset_open();
        $this->filter_section_select('theme_id','Тема КЗ:',2,$this->arr_themes);
        if($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы КЗ:',2,$this->arr_themes_section[$this->filter['theme_id']]);
        if(!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$this->arr_orgs_ids);
        if(!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$this->arr_otdel_ids);
        if(!$this->personal_id) $this->filter_section_select_multiple('working_ids','Должность:',2,$this->arr_works_ids);
        $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 create_usl_select_obj($_params,&$options)
    {
        ob_start();
        ?><strong>Фильтры</strong><?
        damp_array($this->filter,1,-1) ;

        // 1. Формируем временную таблицу всех сотрудников организации, где будет указано сколько вопросов ему необходимо ответить по всем темам в рамках выбранного фильтра
        $this->recs_persons_types=QUIZ()->create_table_quiz_person_rating2($this->filter) ;

        $options_func=[] ;
        if($this->time_from) $options_func['time_from']=$this->time_from;
        if($this->time_to) $options_func['time_to']=$this->time_to;

        // создания временной таблицы рейтингов по заданным фильтрам
        $this->table_quiz_person_rating=QUIZ()->create_table_quiz_person_rating($this->filter,$options_func) ;

        // 2. Формируем условия для выборки из временной таблицы рейтингов по заданным фильтрам
        $_usl=[] ;
        $_usl[]='t1.parent2>0' ;
        //$_usl[]='t1.count_question_get>='.$this->min_questions_get ;
        //$_usl[]='sum_count_question_get>='.$this->min_questions_get ;

         if (_sizeof($this->filter['org_ids']))
        {
            $ids=implode(',',array_keys($this->filter['org_ids']));
            $_usl[]='t1.person_parent2 in ('.$ids.')';
          }

         if (_sizeof($this->filter['otdel_ids']))
        {
            $ids=implode(',',array_keys($this->filter['otdel_ids']));
            $_usl[]='(t1.person_parent3 in ('.$ids.') or t1.person_parent4 in ('.$ids.') or t1.person_parent5 in ('.$ids.') or t1.person_parent6 in ('.$ids.') )';
        }

        if(_sizeof($this->filter['working_ids']))
        {
            $ids=implode(',',array_keys($this->filter['working_ids']));
            $_usl[]='t1.person_working in ('.$ids.')';
          }

        $usl_res=implode(' and ',$_usl) ;
        //echo 'Условия отбора для фильтрации по таблице рейтинга:' ;
        //damp_array($_usl,1,-1) ;

        //damp_array($_usl_select_events,1,-1) ;
        $text=ob_get_clean() ;
        //$this->debugs[]=$text ;
        return($usl_res) ;
     }

    function panel_info_filter()
    {
        $_str=array();
        $title='';
      $info=$this->get_arr_info_filters() ;
      if ($this->filter['theme_id'])                        $info['Тема КЗ']=QUIZ()->get_theme_name_by_id($this->filter['theme_id']);
      if ($this->filter['section_id'])                      $info['Раздел КЗ']=QUIZ()->get_theme_name_by_id($this->filter['section_id']);

      if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
        if(_sizeof($_str)) $title='<div class="center">'.implode(' ',$_str).'</div>';
      return $title ;
      }

    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([]) ;}

  var $recs_personal_rating ;
  var $recs_union_rating ;
  var $arr_itog_themes ;
  var $rat1_info ;
  var $rat2_info ;

    function prepare_data()
    {  ob_start() ;
       $rec_personal=$this->personal_rec ;
       //damp_array($rec_personal);
       // if (!$this->filter['theme_id']) $fname='parent2' ;
       // else if (!_sizeof($this->filter['section_ids'])) $fname='parent3' ;
       // else $fname='parent4' ;

        //echo '$fname='.$fname.'<br>' ;
       if (!$this->filter['theme_id']) $arr_theme_ids=execSQL_row('select pkey,level from quiz_themes where level=2 and enabled=1') ;
       else if ($this->filter['theme_id'] and !_sizeof($this->filter['section_ids'])) $arr_theme_ids=execSQL_row('select pkey,level from quiz_themes where parent2='.$this->filter['theme_id'].' and enabled=1') ;

       //print_r($arr_theme_ids) ; $arr_itog_themes=[] ;
       if (_sizeof($arr_theme_ids)) foreach($arr_theme_ids as $theme_id=>$theme_level)
       {
           // 1. получаем отчет по рейтингу сотрудников по указанной теме КЗ
           $report_obj=new report_quiz_persons_rating() ;
           $report_obj->filter['theme_id']=$theme_id ;
           $report_obj->debug=$this->debug ;
           $report_obj->sql_comment='Получаем таблицу рейтингов сотрудников по теме ID '.$theme_id ;
           $options=[] ;
           $usl=$report_obj->create_usl_select_obj([],$options) ;
           $recs_personals_rating=$report_obj->get_items_easy($usl) ;

           if ($this->debug) $this->debugs=array_merge($this->debugs,$report_obj->debugs) ;

           // считаем суммарные значения и вытаскиваем данные текущего сотрудника
           $yes=0 ;
           $arr_itog=[] ; $arr_person=[] ;
           foreach($recs_personals_rating as $rec_rating)
           { $arr_itog['ball'][]=$rec_rating['ball'] ;
             $arr_itog['proc_pokr'][]=$rec_rating['proc_pokr'] ;
             $arr_itog['rating'][]=$rec_rating['rating'] ;
             if ($rec_rating['personal_id']==$this->personal_id)
              { $yes=1 ;
                $arr_person['ball']=$rec_rating['ball'] ;
                $arr_person['proc_pokr']=$rec_rating['proc_pokr'] ;
                $arr_person['rating']=$rec_rating['rating'] ;

              }
           }

           if ($yes)
           { $this->arr_itog_themes[$theme_id]['ball']=_sizeof($arr_itog['ball'])? round(array_sum($arr_itog['ball'])/_sizeof($arr_itog['ball'])):0 ;
             $this->arr_itog_themes[$theme_id]['proc_pokr']=_sizeof($arr_itog['proc_pokr'])? round(array_sum($arr_itog['proc_pokr'])/_sizeof($arr_itog['proc_pokr'])):0 ;
             $this->arr_itog_themes[$theme_id]['rating']=_sizeof($arr_itog['rating'])? round(array_sum($arr_itog['rating'])/_sizeof($arr_itog['rating'])):0 ;
             $this->arr_itog_themes[$theme_id]['person_ball']=round($arr_person['ball']) ;
             $this->arr_itog_themes[$theme_id]['person_proc_pokr']=round($arr_person['proc_pokr']) ;
             $this->arr_itog_themes[$theme_id]['person_rating']=round($arr_person['rating']) ;
             $rec_theme=QUIZ()->get_theme_by_id($theme_id) ;
             $this->arr_itog_themes[$theme_id]['theme_name']=$rec_theme['obj_name'] ;
             //damp_array($arr_itog) ;
           }
       }

       // получаем место сотруднику по всем темам по должности
       $report_obj=new report_quiz_persons_rating() ;
       $report_obj->filter['working_ids'][$rec_personal['working']]=1 ;
       $report_obj->debug=$this->debug ;
       $report_obj->sql_comment='Получаем таблицу рейтингов сотрудников по должности ID '.$rec_personal['working'] ;
       $options=[] ;
       $usl=$report_obj->create_usl_select_obj([],$options) ;
       $recs=$report_obj->get_items_easy($usl) ;
       //print_2x_arr($recs);
       //if ($rec_personal['working'])
           if (_sizeof($recs)) foreach($recs as $i=>$rec) if ($rec['personal_id']==$this->personal_id)
           { $this->rat1_info='Ваше место в рейтинге сотрудников по должности "<strong>'.$rec_personal['_work_name'].'</strong>"<br><span style="font-size:24px;">'.($i+1).'</span> из <span style="font-size:20px;">'._sizeof($recs).'</span>' ;
             //$this->rat1_info.='<br><br>(процент правильных ответов <strong>'.round($rec['ball'],1).'%</strong>, процент покрытия темы <strong>'.round($rec['proc_pokr'],1).'</strong>%)' ;
           }

        if ($this->debug) $this->debugs=array_merge($this->debugs,$report_obj->debugs) ;

       // получаем место сотруднику по всем темам по подразделению
       $report_obj=new report_quiz_persons_rating() ;
       $report_obj->debug=$this->debug ;
       $report_obj->sql_comment='Получаем таблицу рейтингов сотрудников по организации ID '.$rec_personal['parent2'].' и подразделению '.$rec_personal['parent'] ;
       $report_obj->filter['org_ids'][$rec_personal['parent2']]=1 ;
       $report_obj->filter['otdel_ids'][$rec_personal['parent']]=1 ;
       $options=[] ;
       $usl=$report_obj->create_usl_select_obj([],$options) ;
       $recs=$report_obj->get_items_easy($usl) ;
       //print_2x_arr($recs);
       if (_sizeof($recs)) foreach($recs as $i=>$rec) if ($rec['personal_id']==$this->personal_id)
           { $this->rat2_info='Ваше место в рейтинге сотрудников по подразделению "<strong>'.str_replace('<br>',' / ',$rec_personal['_otdel_name']).'</strong>"<br><span style="font-size:24px;">'.($i+1).'</span> из <span style="font-size:20px;">'._sizeof($recs).'</span>' ;
         //$this->rat2_info.='<br>(процент правильных ответов <strong>'.round($rec['ball'],1).'%</strong>, процент покрытия темы <strong>'.round($rec['proc_pokr'],1).'</strong>%)' ;
         $this->rat2_info.='<br><br><br>Процент правильных ответов <strong>'.round($rec['ball'],1).'%</strong>, процент покрытия темы <strong>'.round($rec['proc_pokr'],1).'</strong>%' ;
           }

       if ($this->debug) $this->debugs=array_merge($this->debugs,$report_obj->debugs) ;

       $this->debugs[]=ob_get_clean() ;



    }



    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'] ;

        //list($theme_ids,$arr_result)=
        $this->prepare_data();

        //print_2x_arr($list_recs);
        //return ;

        ?><div id="chart-container"></div>
        <script type="text/javascript">
                    $j(document).ready(function() {
                        let chart = new FusionCharts({
                            type: 'mscolumn2d',
                            renderAt: 'chart-container',
                            width: '100%',
                            height: '400',
                            dataFormat: 'json',
                            dataSource: {
                                "chart": {
                                    "caption": "Рейтинг",
                                    "subCaption": "",
                                    "theme": "fusion",
                                    "showvalues": "1",
                                    "numberSuffix": "%",
                                    "plotfillalpha": "60",
                                    "yAxisMaxValue": "100",
                                    "yAxisMinValue": "100",
                                    "showBorder" : "0",
                                    "bgColor" : "#ffffff",

                                    xaxisname: "Тема/Раздел КЗ",
                                    yaxisname: "% правильных ответов",
                                    formatnumberscale: "1",
                                    plottooltext: "<b>$dataValue</b> apps were available on <b>$seriesName</b> in $label",
                                    drawcrossline: "1"
                                },
                                // Chart Data
                                categories: [
                                    {
                                        category: [ <? foreach ($this->arr_itog_themes as $theme_id=>$rec) { echo '{"label": "'.$rec['theme_name'].'"},';} ?>]
                                    }
                                ],
                                dataset: [
                                    {
                                        seriesname: "Рейтинг сотрудника",
                                        data: [ <? foreach ($this->arr_itog_themes as $theme_id=>$rec)
                                                    {   $color=($rec['person_rating']>=$rec['rating'])? '#1F972B':'#A30A06' ;
                                                        echo '{color: "'.$color.'","value": "'.$rec['person_rating'].'"},';}
                                                ?>
                                              ]
                                    },
                                    {
                                        seriesname: "Средний рейтинг",
                                        color: "#2da5da",
                                        data: [ <? foreach ($this->arr_itog_themes as $theme_id=>$rec) { echo '{"value": "'.$rec['rating'].'"},';} ?>]
                                    },

                                ],

                            }
                        });

                        chart.render();
                    });
        </script>

                <?
        ?><div class="center"><?
        echo $this->rat1_info.'<br><br>' ;
        echo $this->rat2_info.'<br>' ;
        ?></div><?


        //echo '<br><br><br>' ;
        //echo '$this->debug='.$this->debug.'<br>' ;
        if ($this->debug) echo implode('<br>',$this->debugs) ;
        //print_2x_arr($list_recs);

//        execSQL('select * from '.$this->table_quiz_person_rating.' where personal_id='.$this->personal_id,2,1) ;

        return ;
        //$recs_personal_rating=$this->prepare_data();

        //return ;

        //$chart_arr=$this->prepare_chart_data($theme_ids,$arr_result);

        //$this->print_charts($chart_arr);
//        $this->print_charts2($chart_arr);

        // число вопросов сотруднику необходимо считать с учетом условий отбора вопросов для каждого сотрудника п

        if (_sizeof($this->filter['section_ids']))
                     {   $section_ids=implode(',',array_keys($this->filter['section_ids'])) ;
                         $_usl[]='(t2.parent3 in ('.$section_ids.') or t2.parent4 in ('.$section_ids.') or t2.parent5 in ('.$section_ids.') or t2.parent6 in ('.$section_ids.') )' ;
                     }
        elseif ($this->filter['theme_id'])
        { // cчитаем число вопросов в теме - оно одинаоковое для всех сотрудников
          //$cnt_questions=execSQL_value('select count(pkey) from quiz_questions where parent2='.$this->filter['theme_id']) ;

        }
        else
        {
          //$cnt_questions=execSQL_value('select count(pkey) from quiz_questions where parent2='.$this->filter['theme_id']) ;
        }




    }

    /**
     * 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);
    }





}

?>
