<?php

class report_quiz_persons_rating extends c_report
{
    var $title='Результаты контроля знаний - рейтинг';
    var $personal_id=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 $debugs=[];
    var $arr_orgs_ids;
    var $arr_otdel_ids;
    var $arr_works_ids;
    var $arr_themes;
    var $arr_themes_section;
    var $recs_persons_types;
    var $debug=0 ;
    var $table_quiz_person_rating='' ;
    var $sql_comment='' ;

    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;
        }

    }

    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);
        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 prepare_setting_arr()
    {
        $this->arr_orgs_ids=PERSONAL()->get_arr_orgs_to_cur_account();
        $this->arr_otdel_ids=(_sizeof($this->filter['org_ids']))? PERSONAL()->get_arr_otdels_to_cur_account($this->filter['org_ids']):array();
        $this->arr_works_ids=PERSONAL()->get_arr_working_by_usl($this->filter['org_ids'],$this->filter['otdel_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';

        // получаем список все ids тем/разделов тем, по которым есть результаты КЗ
        $parent_themes=execSQL('select t2.parent2,t2.parent3,t2.parent4,t2.parent5,t2.parent6 
                                from quiz_result t1 
                                inner join quiz_questions t2 on t2.pkey=t1.question_id
                                where '.$usl_theme_select.'
                                group by t2.parent2,t2.parent3,t2.parent4,t2.parent5,t2.parent6
        ',0,1);
        $arr_ids=[] ;
        if (_sizeof($parent_themes)) foreach($parent_themes as $rec) for($i=2;$i<=6;$i++) $arr_ids[$rec['parent'.$i]]++ ;

        // получаем список всех тем
        //$this->arr_themes=TREE('quiz_themes')->get_list_strukture('clss in (1,472) and level in (1,2)',null,1,['hide_parent_name'=>0]) ;
        $this->arr_themes=execSQL_row('select pkey,obj_name from quiz_themes where level=2 and enabled=1 order by obj_name') ;
        // удаляем из списка тем, темы которых нет в результатах КЗ
        if (_sizeof($this->arr_themes_section)) foreach($this->arr_themes_section as $key=>$theme) if(!isset($arr_ids[$key])) unset($this->arr_themes_section[$key]) ;
        // если выбрана тема - получаем список дочерних подразделов
        if($this->filter['theme_id'])
        { $this->arr_themes_section=TREE('quiz_themes')->get_list_strukture('clss in (1,472) and parent2='.$this->filter['theme_id'],null,0,['parent_id'=>$this->filter['theme_id']]) ;
           // удаляем из списка разделы тем, темы которых нет в результатах КЗ
           if (_sizeof($this->arr_themes_section)) foreach($this->arr_themes_section as $key=>$theme) if(!isset($arr_ids[$key])) unset($this->arr_themes_section[$key]) ;
        }
        //damp_array($this->arr_themes_section);
    }

    var $table_quiz_person_rating2 ;

    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) ;
        $this->table_quiz_person_rating2=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;
        if (!$this->filter['theme_id']) $options_func['use_usl_tqs']=1 ;

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



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

        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();
        //echo $text ;
        $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())
    {
        $options['debug']=0;
        $arr=execSQL_row('select t1.personal_id
                          from  '.$this->table_quiz_person_rating.' t1
                          where '.$usl.'
                          group by t1.personal_id
                          ',$options);

        //execSQL('select * from '.$this->table_quiz_person_rating,2) ;
        return (_sizeof($arr));
    }

    function get_items($usl,$options=array())
    {
        $limit=($options['limit'])? ' '.$options['limit']:'';
        $options['debug']=0;
        $options['no_indx']=1;
        $order=($options['order'])? ' order by '.$options['order']:' order by ball desc';

        // если смотрим по разделу, то можем посчитать рейтинг сотрудника на основе процента покрытия раздела и кол-ва правильных вопросов
        if ($this->sql_comment) $this->sql_comment="/* $this->sql_comment */\n" ;
        $recs_personal_rating=execSQL($this->sql_comment.
                        'select t1.personal_id,t1.obj_name as person_name,t1.person_working,t1.person_parent2,t1.person_parent3,t1.person_parent4,t1.person_parent5,t1.person_parent6,
                         t_pers.parent as person_parent_id,   
                         t_works.obj_name as work_name,   
                         sum(t1.count_question_get) as sum_count_question_get,
                         sum(t1.count_question_get_uni) as sum_count_question_get_uni,
                         sum(t1.count_correct) as count_correct,
                         (sum(t1.count_correct)/ sum(t1.count_question_get)*100) as ball,
                         min(min_time) as min_time, 
                         max(max_time) as max_time,
                         t1.theme_cnt_questions,t1.theme_cnt_questions_id,
                         (sum(t1.count_question_get_uni)/t1.theme_cnt_questions*100) as proc_pokr,
                         (sum(t1.count_correct)/ sum(t1.count_question_get)*100+sum(t1.count_question_get_uni)/t1.theme_cnt_questions*100)/2 as rating
                         from '.$this->table_quiz_person_rating.' t1
                         left join  obj_site_personals t_pers on t_pers.pkey=t1.personal_id
                         left join  view_IL_works t_works on t_works.id=t1.person_working
                         where '.$usl.'
                         group by t1.personal_id
                         order by rating desc
                         '.$limit,$options,2,1);

        return ($recs_personal_rating);
    }

    function get_items_easy($usl,$options=array())
    {
        $limit=($options['limit'])? ' '.$options['limit']:'';
        $options['debug']=0;
        $options['no_indx']=1;

        // если смотрим по разделу, то можем посчитать рейтинг сотрудника на основе процента покрытия раздела и кол-ва правильных вопросов
        if ($this->sql_comment) $this->sql_comment="/* $this->sql_comment */\n" ;
        $recs_personal_rating=execSQL($this->sql_comment.
                        'select t1.personal_id,
                         (sum(t1.count_correct)/ sum(t1.count_question_get)*100) as ball,
                         (sum(t1.count_question_get_uni)/t1.theme_cnt_questions*100) as proc_pokr,
                         (sum(t1.count_correct)/ sum(t1.count_question_get)*100+sum(t1.count_question_get_uni)/t1.theme_cnt_questions*100)/2 as rating
                         from '.$this->table_quiz_person_rating.' t1
                         where '.$usl.'
                         group by t1.personal_id
                         order by rating desc
                         '.$limit,$options,2,1);

        return ($recs_personal_rating);
    }

    function print_template_HTML($list_recs,$options=array())
    {
        $id=($options['id'])? 'id='.$options['id']:'';

        $arr_org_otdels=TREE('obj_site_personals')->get_list_strukture('clss in (1,207,208)');
        $arr_quiz_themes=TREE('quiz_themes')->get_list_strukture('clss in (1,472)');
        //damp_array($arr_quiz_themes);

        $quiz_by_inrm_stats=execSQL('select * from '.$this->table_quiz_person_rating2) ;


        ?>
    <table class="basic fz_small full auto"<? echo $id ?>>
        <tr>
        <th>Место в рейтинге</th>
        <th>ФИО</th>
        <th>Организация / Подразделение<br>Должность</th>
        <th>Темы КЗ, подлежащие контролю<br></th>
        <th>Дата первого/последнего опроса</th>
        <th>Число вопросов в теме/разделе</th>
        <th>Число заданных вопросов</th>
        <th>Число заданных вопросов (уникальных)</th>
        <th>Число правильных ответов</th>
        <? if($this->show_learned_stats)
            {
                ?><th>Кол-во переспросов</th>
                  <th>Процент усваиваемости</th>
                <?
            }
        ?><th>Процент покрытия темы/раздела</th>
          <th>Процент правильных ответов</th>
          <th>Рейтинг сотрудника</th>
        </tr><?
        $i=1; $arr_itog=[] ;
        if(_sizeof($list_recs)) foreach($list_recs as $rec)
        {   $proc_pokr=0 ;
            // временная заплатка для случаев, когда сотрудник ответил на большее число вопросов, xем требуется по его должности
            if ($rec['sum_count_question_get_uni']>$rec['theme_cnt_questions']) $rec['sum_count_question_get_uni']=$rec['theme_cnt_questions'] ;
            if ($rec['rating']>100) $rec['rating']=100 ;

            if ($rec['theme_cnt_questions']) $proc_pokr=round($rec['sum_count_question_get_uni']/$rec['theme_cnt_questions']*100,1) ;
            ?>
            <tr>
                <td class="center"><? echo $i;
                    $i++; ?></td>
                <td class="left">
                    <a href="/window/personal/person/<? echo $rec['personal_id'] ?>/quiz/rating/" class="new_window"><? echo $rec['person_name'] ?></a>
                </td>
                <td class="left">
                    <div  style="white-space: nowrap;"><? echo $arr_org_otdels[$rec['person_parent_id']] ?></div>
                    <span class="gray small"><? echo $rec['work_name'] ?></span>
                </td>
                <td class="left"><?
                    $quiz_by_inrm_rec=$quiz_by_inrm_stats[$rec['theme_cnt_questions_id']] ;
                    if ($quiz_by_inrm_rec['themes_ids'])
                    { $arr_themes_ids=explode(',',$quiz_by_inrm_rec['themes_ids']) ;
                      $arr_themes_question_count=explode(',',$quiz_by_inrm_rec['themes_ids_qc']) ;
                      foreach($arr_themes_ids as $ii=>$theme_id)
                      {   $theme_name=$arr_quiz_themes[$theme_id] ;
                          $cnt=$arr_themes_question_count[$ii] ;
                          if ($cnt) echo '<div  style="white-space: nowrap;">- '.$theme_name.' <span class="gray small">['.$cnt.']</span><div>' ;
                      }
                    }
                ?>
                </td>
                <td class="center"><? if($rec['min_time']) echo date('d.m.Y H:i',$rec['min_time']) ?><br><? if($rec['max_time']) echo date('d.m.Y H:i',$rec['max_time']) ?></td>
                <td class=""><? echo $rec['theme_cnt_questions'] ?></td>
                <td class=""><? echo $rec['sum_count_question_get'] ?></td>
                <td class=""><? echo $rec['sum_count_question_get_uni'] ?></td>
                <td class=""><? echo $rec['count_correct'] ?></td>
                <? if($this->show_learned_stats)
                {
                    ?>
                    <td class=""><? echo $rec['cnt_learned_get'] ?></td>
                    <td class=""><? echo $rec[''] ?></td><?
                } ?>
                <td class=""><? if($proc_pokr) echo $proc_pokr.'%' ; $arr_itog['proc_pokr'][]=$proc_pokr ;?></td>
                <td class=""><? if($rec['ball']) echo round($rec['ball']).'%' ; $arr_itog['ball'][]=$rec['ball'] ;?></td>
                <td class=""><? if($rec['rating']) echo round($rec['rating'],1) ; $arr_itog['rating'][]=$rec['rating'] ;?></td>
            </tr>
            <?
        }
        ?><tr><td colspan="9" class="right">СРЕДНИЙ БАЛЛ: </td>
              <td><?echo (_sizeof($arr_itog['proc_pokr']))? round(array_sum($arr_itog['proc_pokr'])/_sizeof($arr_itog['proc_pokr'])).'%':'-'?></td>
              <td><?echo (_sizeof($arr_itog['ball']))? round(array_sum($arr_itog['ball'])/_sizeof($arr_itog['ball'])).'%':'-'?></td>
              <td><?echo (_sizeof($arr_itog['rating']))? round(array_sum($arr_itog['rating'])/_sizeof($arr_itog['rating'])).'%':'-'?></td>
        </tr><?
        ?></table><?

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

         // execSQL('select * from '.$this->table_quiz_person_rating.' limit 10',2,1);
        }
    }
}

?>
