<?php
class report_quiz_rmr_stats extends c_report
{
    public $use_fusioncharts=1 ;
    var $view_graf=1 ;
    var $title='Результаты контроля знаний - статистика' ;
    var $personal_id=0 ;
    var $event_id=0 ;
    var $view_mode=array(1=>'90 дней',2=>'180 дней',3=>'1 год',4=>'все время') ;
//    var $time_int=array(1=>'Cутки',2=>'Неделя',3=>'Месяц') ;
    var $usl_time ;
    var $time_from ;
    var $time_to ;
    var $usl_quiz_result ;

    function init($crete_options=array()) {
//        $cnt_day = ($this->filter['cnt_days']) ? (int)$this->filter['cnt_days'] : 0;
        $view_mode = ($this->filter['view_mode'] ? (int)$this->filter['view_mode'] : 1);
        $tt = getdate();
        $this->time_from = 0;
        $this->time_to = mktime(0,0,0,$tt['mon'],$tt['mday']+1,$tt['year']) - 1;

        switch($view_mode) {
            case 2:
                $this->time_from = mktime(0,0,0,$tt['mon'],$tt['mday']-180,$tt['year']) ;
                $this->usl_time = 'and 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 = 'and t1.quiz_с_data>='.$this->time_from;
                break ;
            case 4:
                $this->time_from = execSQL_value('select min(quiz_с_data) from view_quiz_result');
                $this->usl_time='' ;
                break ;
            case 1:
            default:
                $this->time_from = mktime(0,0,0,$tt['mon'],$tt['mday']-90,$tt['year']);
                $this->usl_time = 'and t1.quiz_с_data>='.$this->time_from;
                break ;
        }
    }

    function setting() {
        $arr_orgs_ids = PERSONAL()->get_arr_orgs_to_cur_account();
        $arr_otdel_ids = (_sizeof($this->filter['org_ids'])) ? PERSONAL()->get_arr_otdels_to_cur_account($this->filter['org_ids']) : [];

        $_usl = [];
        $_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 quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
//                damp_array($section_ids);
            } else {
                $section_ids = array_keys($this->filter['section_ids']);
//                damp_array($section_ids);
            }

//            if ($section_ids and !_sizeof($this->filter['question_ids'])) {
//                $questions_ids = execSQL_line('select pkey as id from quiz_questions where parent in ('.implode(',',$section_ids).')') ;
//            }

            if(_sizeof($this->filter['question_ids'])) {
                $questions_ids = array_keys($this->filter['question_ids']);
            } elseif (!_sizeof($this->filter['question_ids']) and _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) : '';

        // получаем список всех ТЕМ вопросов, которые задавались сотруднику
        $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,
                             t2.pkey as question_id, t2.obj_name as question_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,t2.pkey
                             order by t4.indx,t3.indx,t2.indx
                             ',0,1);

        $arr_themes = [];
        $arr_themes_section = [];
//        $arr_section_questions = [];

        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'];
//                $arr_section_questions[$rec['theme_id']][$rec['section_id']][$rec['question_id']] = $rec['question_name'];
            }
        }



        $this->form_open() ;

        $this->row_open() ;
        $this->fieldset_open() ;
        $this->filter_section_select('theme_id','Тема КЗ:',2,$arr_themes) ;
        $this->filter_section_select_multiple('section_ids','Разделы КЗ:',2,$arr_themes_section[$this->filter['theme_id']]) ;
//        if($this->filter['section_id']) $this->filter_section_select_multiple('question_ids','Вопросы КЗ:',4,$arr_section_questions[$this->filter['theme_id']][$this->filter['section_id']]) ;
        $this->filter_section_select('view_mode','Период:',1,$this->view_mode,['nospace_element'=>1]) ;
//        $this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element')) ;
        $this->fieldset_close() ;
        $this->row_close() ;

        $this->row_open() ;
        $this->fieldset_open() ;
        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->fieldset_close() ;
        $this->row_close();

        $this->panel_buttons();

        $this->form_close() ;
    }

    function get_arr_info_filters() {
        $info=parent::get_arr_info_filters() ;
        if (!$this->filter['view_mode'])                      $info['временной интервал']=$this->view_mode['1'] ;
        else                                                  $info['временной интервал']=$this->view_mode[$this->filter['view_mode']] ;
//        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 (_sizeof($this->filter['section_ids']))              $info['Разделы КЗ']=QUIZ()->get_theme_name_by_id($this->filter['section_ids']);
//        if (_sizeof($this->filter['question_ids']))            $info['Вопросы КЗ']=QUIZ()->get_question_name_by_ids(implode(',',array_keys($this->filter['question_ids'])));
        if ($this->filter['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
        if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
        if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
        if ($this->filter['otdel_id'])                        $info['подразделение']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
        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 = []) {

        // получаем список всех ТЕМ вопросов, которые задавались сотруднику
        $theme_ids = execSQL('select t3.parent as theme_id, count(distinct(t1.question_id)) as questions_cnt,t4.obj_name as theme_name 
                        from view_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.parent 
                        left join '.MEMBER()->personal_viewer_name.' tp on tp.pkey=t1.personal_id
                        where ' . $this->usl_quiz_result . ' ' . $this->usl_time . ' and not tp.pkey is null '. $usl_str.'
                        group by t3.parent', 0);

//        $theme_stats = execSQL('select t3.parent as theme_id,t3.pkey as section_id,t1.correct,count(t1.quiz_result_id) as cnt,t3.obj_name as section_name
//                          from view_quiz_result t1
//                          left join quiz_questions t2 on t2.pkey=t1.question_id
//                          left join quiz_themes t3 on t3.pkey=t2.parent
//                          where ' . $this->usl_quiz_result . ' ' . $this->usl_time . '
//                          group by t3.parent,t2.parent,t1.correct ', 0, 1);

        $sections_stats = [];
        $sections_stats = execSQL('select t3.pkey as section_id, t3.parent as theme_id,sum(t1.correct) as correct_cnt,count(t1.quiz_result_id) as cnt,t3.obj_name as section_name 
                          from view_quiz_result t1 
                          left join quiz_questions t2 on t2.pkey=t1.question_id
                          left join quiz_themes t3 on t3.pkey=t2.parent
                          where ' . $this->usl_quiz_result . ' ' . $this->usl_time . ' ' . $usl_str.'
                          group by t3.parent,t2.parent ', 0);


        $questions_stats = [];
        if($this->filter['theme_id']) {
            $questions_stats = execSQL('select t3.pkey as question_id, t3.parent as section_id, sum(t1.correct) as correct_cnt, count(t3.pkey) as cnt, t3.obj_name as question_name
                          from view_quiz_result t1
                          left join quiz_questions t3 on t3.pkey=t1.question_id
                          where ' . $this->usl_quiz_result . ' ' . $this->usl_time . ' ' . $usl_str.'
                          group by t3.parent,t3.pkey ', 0);
        }

        //кол-во вопросов в теме/разделе
//        $theme_stats_full = execSQL('select t3.parent as theme_id,t2.parent as section_id,count(t2.pkey) as cnt
//                               from quiz_questions t2
//                               left join quiz_themes t3 on t3.pkey=t2.parent
//                               group by t3.parent,t2.parent', 0, 1);


//        damp_array($theme_ids);
//        damp_array($sections_stats);
//        damp_array($questions_stats);

        $arr_result = [
            'level_1' => [],
            'level_2' => [],
        ];
        $arr_charts = [];

        if(!$this->filter['theme_id']){
            if (_sizeof($sections_stats)) {
                foreach ($sections_stats as $rec) {
                    $arr_result['level_1'][$rec['theme_id']]['cnt'] += $rec['cnt'];
                    $arr_result['level_1'][$rec['theme_id']]['correct_cnt'] += $rec['correct_cnt'];

                    $arr_result['level_2'][$rec['theme_id']][$rec['section_id']]['name'] = $rec['section_name'];
                    $arr_result['level_2'][$rec['theme_id']][$rec['section_id']]['cnt'] = $rec['cnt'];
                    $arr_result['level_2'][$rec['theme_id']][$rec['section_id']]['correct_cnt'] = $rec['correct_cnt'];

                    $level_2_correct_proc = $rec['correct_cnt'] / $rec['cnt'] * 100;
                    $level_2_correct_proc = ($level_2_correct_proc >= 1 ? round($level_2_correct_proc) : round($level_2_correct_proc, 1));
                    $arr_result['level_2'][$rec['theme_id']][$rec['section_id']]['correct_proc'] = $level_2_correct_proc;

                }
            }

            if (_sizeof($theme_ids)) {
                foreach ($theme_ids as $theme) {
                    $i = $theme['theme_id'];
                    if(_sizeof($arr_result['level_1'][$i])) {
                        $arr_result['level_1'][$i]['name'] = $theme['theme_name'];
                        if(!$arr_result['level_1'][$i]['cnt']) $arr_result['level_1'][$i]['cnt'] = '0';
                        if(!$arr_result['level_1'][$i]['correct_cnt']) $arr_result['level_1'][$i]['correct_cnt'] = '0';

                        $level_1_correct_proc = $arr_result['level_1'][$i]['correct_cnt'] / $arr_result['level_1'][$i]['cnt'] * 100;
                        $level_1_correct_proc = ($level_1_correct_proc >= 1 ? round($level_1_correct_proc) : round($level_1_correct_proc, 1));
                        $arr_result['level_1'][$i]['correct_proc'] = $level_1_correct_proc;

                        //для графиков
                        $arr_charts['radar']['category'][] = $theme['theme_name'];
                        $arr_charts['radar']['data'][] = $level_1_correct_proc;
                    }
                }
            }
        } elseif($this->filter['theme_id']) {
            if(_sizeof($sections_stats)) {
//                damp_array($sections_stats);
                foreach ($sections_stats as $rec) {
                    $arr_result['level_1'][$rec['section_id']]['cnt'] = $rec['cnt'];
                    $arr_result['level_1'][$rec['section_id']]['correct_cnt'] = $rec['correct_cnt'];
                    $arr_result['level_1'][$rec['section_id']]['name'] = $rec['section_name'];

                    $level_1_correct_proc = $rec['correct_cnt'] / $rec['cnt'] * 100;
                    $level_1_correct_proc = ($level_1_correct_proc >= 1 ? round($level_1_correct_proc) : round($level_1_correct_proc, 1));
                    $arr_result['level_1'][$rec['section_id']]['correct_proc'] = $level_1_correct_proc;


                    // если установлен фильтр по одному разделу,
                    // то радар формируется на данных вопросов, находящихся в выбранном разделе,
                    // если фильтр по двум и более разделам,
                    // то радар формируется на общих данных разделов

                    if(_sizeof($sections_stats) >= 2) {
                        if(!_sizeof($this->filter['section_ids']) or _sizeof($this->filter['section_ids']) >= 2) {
                            //для графиков
                            $arr_charts['radar']['category'][] = $rec['section_name'];
                            $arr_charts['radar']['data'][] = $level_1_correct_proc;
                        }
                    }

                }
            }

            if(_sizeof($questions_stats)) {
//                damp_array($questions_stats);
                foreach ($questions_stats as $rec) {
                    $arr_result['level_2'][$rec['section_id']][$rec['question_id']]['cnt'] = $rec['cnt'];
                    $arr_result['level_2'][$rec['section_id']][$rec['question_id']]['correct_cnt'] = $rec['correct_cnt'];
                    $arr_result['level_2'][$rec['section_id']][$rec['question_id']]['name'] = $rec['question_name'];

                    $level_2_correct_proc = $rec['correct_cnt'] / $rec['cnt'] * 100;
                    $level_2_correct_proc = ($level_2_correct_proc >= 1 ? round($level_2_correct_proc) : round($level_2_correct_proc, 1));
                    $arr_result['level_2'][$rec['section_id']][$rec['question_id']]['correct_proc'] = $level_2_correct_proc;

                    if(_sizeof($sections_stats) == 1 or _sizeof($this->filter['section_ids']) == 1) {
                        //для графиков
                        $arr_charts['radar']['category'][] = htmlspecialchars($rec['question_name']);
                        $arr_charts['radar']['data'][] = $level_2_correct_proc;
                    }
                }
            }
        }

        $arr_charts['stats'] = [];
        $t = $this->time_from;
        while($t <= $this->time_to) {
            $ts = getdate($t) ;
            $t1 = $t ;
            $cur_month = mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
            $arr_month[$cur_month] = get_month_year($cur_month,'month year') ;
            switch($this->filter['view_mode']) {
                // период 180 дней, разбивка 30 дней
                case 2:
                    $t = mktime(0,0,0,$ts['mon'],$ts['mday']+30,$ts['year']) ;
                    $t2 = $t-1;
                    $i = (date('y', $t1) == date('y', $t2)
                        ? date('d.m', $t1).'-'.date('d.m \'y', $t2)
                        : date('d.m \'y', $t1).'-'.date('d.m \'y', $t2)
                    );
                    break  ;
                // периоды год и все время, разбивка по месяцам
                case 3:
                case 4:
                    $t = mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
                    $t2 = $t-1;
                    $i = get_month_year($t1,'month year') ;
                    break ;
                // по дефолту выбран период 90 дней, разбивка по 10 дней
                case 1:
                default:
                    $t = mktime(0,0,0,$ts['mon'],$ts['mday'] + 10,$ts['year']);
                    $t2 = $t-1;
                    $i = (date('y', $t1) == date('y', $t2)
                        ? date('d.m', $t1).'-'.date('d.m \'y', $t2)
                        : date('d.m \'y', $t1).'-'.date('d.m \'y', $t2)
                    );
                    break ;
            }

            $usl = str_replace('not t3.parent is null', '', $this->usl_quiz_result);
            $usl = trim($usl);
            if($usl === 'and') {
                $usl = '';
            }
            if(strlen($usl) and strpos($usl, 'and') !== 0) {
                $usl = ' and '.$usl;
            } elseif(strlen($usl) and strpos($usl, 'and') === 0) {
                $usl = ' '.$usl;
            }

            $arr_charts['stats'][htmlspecialchars($i)]['count_question'] = execSQL_value('select count(question_id) from view_quiz_result where quiz_с_data>='.$t1.' and quiz_с_data<='.$t2.$usl);
            $arr_charts['stats'][htmlspecialchars($i)]['count_correct'] = execSQL_value('select sum(correct) from view_quiz_result where quiz_с_data>='.$t1.' and quiz_с_data<='.$t2.$usl);
            $arr_charts['stats'][htmlspecialchars($i)]['k1'] = ($arr_charts['stats'][htmlspecialchars($i)]['count_question']) ? round($arr_charts['stats'][htmlspecialchars($i)]['count_correct'] / $arr_charts['stats'][htmlspecialchars($i)]['count_question'] * 100) : 0;
        }

        $this->print_charts($arr_charts);

        $this->create_table_2($arr_result);
    }

    function create_table_2($arr) {
        ?>
        <table class="report_inv basic fz_small full auto" style="table-layout: fixed;max-width: 100%;">
            <tr>
                <th style="width:calc(100% - 210px * 3);">Тема/Раздел</th>
                <th style="width:210px;">Число заданных вопросов</th>
                <th style="width:210px;">Число правильных ответов</th>
                <th style="width:210px;">Процент правильных ответов</th>
                <!--<th>Процент покрытия темы/раздела</th>-->
            </tr>

            <?
            if(_sizeof($arr['level_1'])) {
                foreach ($arr['level_1'] as $level_1_id => $level_1_rec) {
                    ?>
                    <tr class=item style="background-color:rgba(0,80,170,0.76);color:white;">
                        <td class="left"><?echo $level_1_rec['name'];?></td>
                        <td><?echo $level_1_rec['cnt'];?></td>
                        <td><?echo $level_1_rec['correct_cnt'];?></td>
                        <td><?echo $level_1_rec['correct_proc'].'%';?></td>
                    </tr>
                    <?

                    if(_sizeof($arr['level_2'][$level_1_id])) {
                        foreach($arr['level_2'][$level_1_id] as $level_2_id => $level_2_rec) {
                            ?>
                            <tr>
                                <td class="left" style="padding-left: 20px;"><?echo $level_2_rec['name'];?></td>
                                <td><?echo $level_2_rec['cnt'];?></td>
                                <td><?echo $level_2_rec['correct_cnt'];?></td>
                                <td><?echo $level_2_rec['correct_proc'].'%';?></td>
                            </tr>
                            <?
                        }
                    }
                }
            }
            ?>
        </table>
        <?
    }

    function create_table() {
        ?>

        <table class="report_inv basic fz_small full auto"<? echo $id ?>>
            <tr>
                <th>Тема/Раздел</th>
                <th>Число вопросов в теме/разделе</th>
                <th>Число заданных вопросов</th>
                <th style="width:210px;">Процент правильных ответов</th>
                <!--<th>Процент покрытия темы/раздела</th>-->
            </tr>
            <?
            if (_sizeof($theme_ids)) {
                foreach ($theme_ids as $rec) {
                    $theme_id = $rec['theme_id'];
                    $proc1 = ($arr_result[$theme_id]['cnt_questions_get']) ? $arr_result[$theme_id]['cnt_questions_get_correct'] / $arr_result[$theme_id]['cnt_questions_get'] * 100 : 0;
                    $proc1 = ($proc1 >= 1) ? round($proc1) : round($proc1, 1);

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

                    ?>
                    <tr class=item style="background-color:rgba(0,80,170,0.76);color:white;">
                        <td class="left"><? echo $rec['theme_name'] ?></td>
                        <td class=""><? echo $arr_result[$theme_id]['cnt_questions'] ?></td>
                        <td class=""><? echo $arr_result[$theme_id]['cnt_questions_get'] ?></td>
                        <td class=""><? echo $proc1 ?>%</td>
                    </tr>
                    <?

                    if (_sizeof($arr_result[$theme_id]['section_stats'])) {
                        foreach ($arr_result[$theme_id]['section_stats'] as $section_id => $section_info) {
                            $proc1 = $section_info['cnt_questions_get_correct'] / $section_info['cnt_questions_get'] * 100;
                            $proc1 = ($proc1 >= 1) ? round($proc1) : round($proc1, 1);

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

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


                            ?>
                            <tr>
                                <td class="left"><?
                                    echo $section_info['section_name'] ?></td>
                                <td><?
                                    echo $section_info['cnt_questions'] ?></td>
                                <td><?
                                    echo $section_info['cnt_questions_get'] ?></td>
                                <td>
                                    <?
                                    echo $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>

                            </tr>
                            <?
                        }
                    }
                }
            }
            ?>
        </table>
        <?
    }

    function print_charts($arr) {
        ?>
        <div class="charts">
            <div id="radar_chart">Подождите, идет построение графика</div>
            <div id="stats_chart">Подождите, идет построение графика</div>
        </div>
        <style type="text/css">
            .charts{
                display:flex;
                margin:0 auto;
                width:100%;
            }
            .charts > #radar_chart{
                width: 40%;
            }
            .charts > #stats_chart{
                width: 60%;
            }
        </style>
        <?

        $this->create_radar_chart($arr['radar']);
        $this->create_stats_chart($arr['stats']);
    }

    function create_radar_chart($data) {
        if(!_sizeof($data)) return;
//        damp_array($data);
        ?>
        <script type="text/javascript">
            $j(document).ready(function() {
                let radar_chart = new FusionCharts({
                    type: 'radar',
                    renderAt: 'radar_chart',
                    width: '100%',
                    height: '400',
                    dataFormat: 'json',
                    dataSource: {
                        "chart": {
                            // "caption": "Усваиваемость",
                            "subCaption": "",
                            "theme": "fusion",
                            "showvalues": "0",
                            "numberSuffix": "%",
                            "plotfillalpha": "60",
                            "yAxisMaxValue": "100",
                            "yAxisMinValue": "100",
                            "showBorder" : "0",
                            "bgColor" : "#ffffff",
                        },
                        // Chart Data
                        categories: [
                            {
                                category: [ <? foreach ($data['category'] as $value) { echo '{"label": "'.$value.'"},';} ?>]
                            }
                        ],
                        dataset: [
                            {
                                seriesname: "",
                                color: "#2da5da",
                                data: [ <? foreach ($data['data'] as $value) { echo '{"value": "'.$value.'"},';} ?>]
                            }
                        ]
                    }
                });

                radar_chart.render();
            });
        </script>
        <?
    }

    function create_stats_chart($data) {
        if (!_sizeof($data)) return;
//        $data = [
//            '12.05' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '02.05' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '22.04' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '12.04' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '02.04' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '22.03' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '12.03' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '02.03' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ],
//            '22.02' => [
//                'count_question' => '100',
//                'count_correct' => '10',
//                'k1' => '10'
//            ]
//        ];
        $caption='График оценки знаний' ;
//        $t1 = getdate();


        $arr_labels=array_keys($data) ;
        ?>
        <script type="text/javascript">
            $j(document).ready(function(){
                FusionCharts.ready(function(){
                    var revenueChart2 = new FusionCharts({
                        type: 'mscombidy2d',
                        renderAt: 'stats_chart',
                        width: '1000',
                        height: '400',
                        dataFormat: 'json',
                        dataSource: {
                            "chart": {
                                "caption": "<?echo $caption?>",
                                "xAxisname": "Время",
                                "pYAxisName": "Кол-во вопросов/ответов",
                                "sYAxisName": "Уровень знаний, %",
                                //"numberPrefix": "",
                                "sNumberSuffix" : "%",
                                "sYAxisMaxValue" : "100",
                                "sYAxisMaxValue" : "100",

                                //Cosmetics
                                "paletteColors" : "#0075c2,#1aaf5d,#f2c500",
                                "baseFontColor" : "#333333",
                                "baseFont" : "Helvetica Neue,Arial",
                                "captionFontSize" : "14",
                                "subcaptionFontSize" : "14",
                                "subcaptionFontBold" : "0",
                                "showBorder" : "0",
                                "bgColor" : "#ffffff",
                                "showShadow" : "0",
                                "canvasBgColor" : "#ffffff",
                                "canvasBorderAlpha" : "0",
                                "divlineAlpha" : "100",
                                "divlineColor" : "#999999",
                                "divlineThickness" : "1",
                                "divLineIsDashed" : "1",
                                "divLineDashLen" : "1",
                                "divLineGapLen" : "1",
                                "usePlotGradientColor" : "0",
                                "showplotborder" : "0",
                                "showXAxisLine" : "1",
                                "xAxisLineThickness" : "1",
                                "xAxisLineColor" : "#999999",
                                "showAlternateHGridColor" : "0",
                                "showAlternateVGridColor" : "0",
                                "legendBgAlpha" : "0",
                                "legendBorderAlpha" : "0",
                                "legendShadow" : "0",
                                "legendItemFontSize" : "10",
                                "legendItemFontColor" : "#666666"
                            },
                            "categories":
                                [{
                                    "category": [ <?foreach($arr_labels as $label) echo '{ "label": "'.$label.'" },' ; ?>]
                                }],
                            "dataset":
                                [
                                    {
                                        "seriesName": "Задано вопросов",
                                        "showValues": "1",
                                        //"renderAs": "line",
                                        "data": [ <?foreach($data as $values) echo '{ "value" : "'.($values['count_question'] ? $values['count_question'] : 0).'" },'?>]
                                    },
                                    {
                                        "seriesName": "правильных ответов",
                                        //"parentYAxis": "S",
                                        //"renderAs": "line",
                                        "showValues": "1",
                                        "divlineThickness" : "1",
                                        "data": [<?foreach($data as $values) echo '{ "value" : "'.($values['count_correct'] ? $values['count_correct'] : 0).'" },'?>]
                                    },

                                    {
                                        "seriesName": "Уровень знаний, %",
                                        "parentYAxis": "S",
                                        "renderAs": "line",
                                        "showValues": "1",
                                        "divlineThickness" : "1",
                                        "data": [<?foreach($data as $values) echo '{ "value" : "'.($values['k1'] ? $values['k1'] : 0).'" },'?>]
                                    },



                                ]
                        }
                    });

                    revenueChart2.render();
                });
            });
        </script>
        <?
    }

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

}

?>
