<?php
include_once('c_quiz.php') ;
class c_page_cab_quiz_testings extends c_page_cab_quiz
{
 public $h1='КЗ - Тестирование' ;

 function block_main()
 {
   /*?><button class="button v1" cmd="clear_kz_result">Удалить все результаты КЗ</button><?*/
   /*?><button class="button v1" cmd="generate_kz_result">Генерация результатов КЗ</button><?*/
   ?><button class="button v1" cmd="full_result_last">Заполнить поле Last</button><?
   ?><button class="button v1" cmd="show_questions_level_0">Показать вопросы без разделов</button><?
   ?><button class="button v1" cmd="check_structure">Проверить структуру разделов КЗ</button><?
   ?><button class="button v1" cmd="update_stats">Пересоздать таблицы статистики</button><?

     /*include_once(_DIR_EXT.'/quiz/report_quiz_persons_rating.php');
     $report_obj=new report_quiz_persons_rating();
     //$report_obj->personal_id=$this->rec_section['pkey'];
     $report_obj->min_limit=10;
     $report_obj->debug=1;
     $report_obj->init();
     $report_obj->setting();
     $report_obj->view();*/

   return ;



 }

 function CMD_update_stats()
 {
     QUIZ()->update_stats();
 }

 function CMD_check_structure()
{   echo 'Проверяем структуру позразделов<br>' ;
    TREE('quiz_themes')->update_levels_parents('',['ext_table'=>'quiz_questions','debug'=>0]);
    echo 'Проверка структуру выполнена<br>' ;


}


 function CMD_show_questions_level_0()
 {
    $recs=execSQL(
            'select t1.parent as section_id,count(t1.pkey) as count_questions,
             t2.pkey,t2.level,t2.parent2, t2.parent3,t2.parent4,
             t2.obj_name as section_name2,
             t3.obj_name as section_name3,
             t4.obj_name as section_name4,
             t5.obj_name as section_name5
             from quiz_questions t1
             left join quiz_themes t2 on t2.pkey=t1.parent
             left join quiz_themes t3 on t3.pkey=t2.parent
             left join quiz_themes t4 on t4.pkey=t3.parent
             left join quiz_themes t5 on t5.pkey=t4.parent
             where t1.level=0 or t1.parent1=0
             group by t1.parent
             ',0,1
    ) ;
    print_2x_arr($recs);
    ?><button class="button v1" cmd="delete_questions_level_0">Удалить вопросы без разделов</button><?
 }

 function CMD_delete_questions_level_0()
 {
     $recs=execSQL(
                 'select t1.parent as section_id,count(t1.pkey) as count_questions,
                  t2.pkey,t2.level,t2.parent2, t2.parent3,t2.parent4,
                  t2.obj_name as section_name2,
                  t3.obj_name as section_name3,
                  t4.obj_name as section_name4,
                  t5.obj_name as section_name5
                  from quiz_questions t1
                  left join quiz_themes t2 on t2.pkey=t1.parent
                  left join quiz_themes t3 on t3.pkey=t2.parent
                  left join quiz_themes t4 on t4.pkey=t3.parent
                  left join quiz_themes t5 on t5.pkey=t4.parent
                  where t1.level=0 or t1.parent1=0
                  group by t1.parent
                  '
         ,0,1) ;
     if (_sizeof($recs)) foreach($recs as $rec) if (!$rec['pkey'])
     {  echo '<strong>Удаяем вопросы удаленного раздела ID '.$rec['section_id'].'</strong><br>' ;
        $arr_ids=execSQL_line('select pkey from quiz_questions where (level=0 or parent1=0) and parent='.$rec['section_id']) ;
        QUIZ()->tiket_delete($arr_ids) ;
     }
 }

 function sync_quiz_result_to_quiz_sessions()
 {

     $recs=execSQL('select t1.*,
                    t3.terminal_pkey,t3.terminal_id,t3.member_id as personal_id,t3.group_id,t3.reader,t3.c_data,t3.e_data,t3.reason,t3.equipment,t3.video,t3.DTW_id,
                    t3.c_data_m,t3.c_data_h,t3.c_data_d, t3.error,t3.error_reason,t3.message_terminal,t3.terminal_comment
                    from quiz_result t1
                    left join quiz_sessions t2 on  t2.mo_id=t1.mo_id
                    left join obj_site_mo_session t3 on  t3.pkey=t1.mo_id
                    where t2.pkey is null and t1.mo_id>0
                   ') ;
     if (!_sizeof($recs)) return ;
     echo 'Найдено <strong>'._sizeof($recs).'</strong> записей в quiz_result, сессии которых отсутстуют в quiz_sessions<br>' ;
     $recs_mo=group_by_field('mo_id',$recs) ;
     if (_sizeof($recs_mo)) foreach($recs_mo as $mo_id=>$quiz_results)
     {
         $mo_info=$quiz_results[0] ;
         $rec_session_kz=array('mo_id'          => $mo_id,
                               'DTW_id'        => $mo_info['DTW_id'],
                               'pass_id'        => $mo_info['pass_id'],
                               'terminal_id'    => $mo_info['terminal_id'],
                               'terminal_pkey'  => $mo_info['terminal_pkey'],
                               'personal_id'    => $mo_info['personal_id'],
                               'group_id'       => $mo_info['group_id'],
                               'reader'         => ($mo_info['reader'])? $mo_info['reader']:'',
                                'c_data'        => $mo_info['c_data'],
                                'e_data'        => $mo_info['e_data'],
                                'c_data_m'        => $mo_info['c_data_m'],
                                'c_data_h'        => $mo_info['c_data_h'],
                                'c_data_d'        => $mo_info['c_data_d'],
                 	            'reason'        => $mo_info['reason'],
                 	            'equipment'     => $mo_info['equipment'],
                 	            'video'         => $mo_info['video'],
                 	            'error'         => $mo_info['error'],
                 	            'error_reason'         => $mo_info['error_reason'],
                 	            'message_terminal'         => $mo_info['message_terminal'],
                 	            'terminal_comment'         => $mo_info['terminal_comment'],
                 	            'status'         => 2,
                 	            'clss'         => 278,
                 	            'indx'         => 1
                               //'pass_id'        => $rec_event_pass['event_pass_id']
                              );
         multiSQL_insert('quiz_sessions')->append($rec_session_kz);
         $arr_sessions[]=$rec_session_kz ;
     }

     //print_2x_arr($arr_sessions);
     multiSQL_insert('quiz_sessions')->flush();

     execSQL_update('update quiz_result t1
                     right join quiz_sessions t2 on t2.mo_id=t1.mo_id
                     set t1.quiz_id=t2.pkey
                     where (t1.quiz_id=0 or t1.quiz_id is null)'
                    ,2) ;




 }

 function CMD_clear_kz_result()
 {

     //execSQL_update('truncate table quiz_sessions') ;
     //execSQL_update('truncate table quiz_sessions_questions') ;
     //execSQL_update('truncate table quiz_result') ;
     //execSQL_update('truncate table quiz_stats') ;
     //execSQL_update('truncate table quiz_learned') ;
     //echo 'Все данные по КЗ удалены<br>' ;

 }

 function CMD_generate_kz_result()
 {
     //damp_array($this->filter,1,-1);
     //if (!$this->filter['name']) return(0) ;
     //$rec_personal=PERSONAL()->get_personal(['obj_name'=>$this->filter['name']]) ;
     //if (!$rec_personal['pkey']) return(0) ;
     //damp_array($rec_personal);
     $rec_personal['pkey']=18159 ;
     // удаляем все результаты КЗ данного сотрудника по указанной теме
     $_usl=[] ;
     $_usl[]='personal_id='.$rec_personal['pkey'] ;
     $root_id=1 ;
     if ($this->filter['theme_id']) $root_id=$this->filter['theme_id'] ;
     if ($this->filter['section_id']) $root_id=$this->filter['section_id'] ;
     $rec_root=execSQL_van('select * from quiz_themes where pkey='.$root_id) ;
     $child_ids=execSQL_line('select pkey from quiz_themes where parent'.$rec_root['level'].'='.$root_id) ;
     $questions_ids=execSQL_line('select pkey from quiz_questions where parent'.$rec_root['level'].'='.$root_id) ;
     $child_ids[]=$root_id ;

     /*if (_sizeof($questions_ids))
     { execSQL_update('delete from quiz_result where personal_id='.$rec_personal['pkey'].' and question_id in ('.implode(',',$questions_ids).')') ;
       execSQL_update('delete from quiz_learned where personal_id='.$rec_personal['pkey'].' and question_id in ('.implode(',',$questions_ids).')') ;

       $session_ids=execSQL_line('select distinct(t1.parent)
                                    from quiz_sessions_questions t1
                                    left join quiz_sessions t2 on t2.pkey=t1.parent
                                    where t2.personal_id='.$rec_personal['pkey'].' and t1.question_id in ('.implode(',',$questions_ids).')') ;

       if (_sizeof($session_ids))
       {   execSQL_update('delete from quiz_sessions_questions where parent in ('.implode(',',$session_ids).') and t1.question_id in ('.implode(',',$questions_ids).')') ;
           execSQL_update('delete from quiz_sessions where pkey in ('.implode(',',$session_ids).')') ;
       }
     }*/

     for ($i=1;$i<10;$i++) $this->generate_quiz_session($rec_personal['pkey']) ;

 }

 function generate_quiz_session($personal_id)
    {
        // добавляем имитацию проведения опроса
        $session_info=['session_id'=>0,'group_id'=>0,'terminal_pkey'=>0,'terminal_id'=>0,'personal_id'=>$personal_id,'debug'=>1,];
        $data=array() ;
        ob_start() ;
        EVENTS()->on_event_server_check_access_success($session_info,$data);
        $text=ob_get_clean() ;
        //damp_array($data);

        // далее самое интересное
        $quiz_id=$data['args']['data']['quiz'] ;
        $questions_ids=execSQL_line('select question_id from quiz_sessions_questions where parent='.$quiz_id) ;
        $recs_answer=execSQL('select * from quiz_answers where parent in ('.implode(',',$questions_ids).')') ;
        if (_sizeof($recs_answer))
        {
            $quiz_result=[] ;
            $quiz_result['quiz_id']=$quiz_id ;
            foreach($recs_answer as $rec_answer)
            {
                $ff=rand(1,10) ;
                $quiz_result['quiz_answers'][$rec_answer['pkey']]=($ff>5)? $rec_answer['status']:0 ;
            }
            // отправляем данные на вход скрипта приема результатов
            $result=IO()->doPut_v3(_PATH_TO_SITE.'/services/quiz/result/',['post'=>$quiz_result]) ;
            if ($result['status']==200) echo 'Результаты КЗ ID '.$quiz_id.' были успешно отправлены<br>' ;
            else damp_array($result,1,-1);
        }
        //damp_array($quiz_result);
        //damp_array($result);
        // получаем ответы на все вопросы
    }


 function CMD_full_result_last()
 {
     $personal_ids=execSQL_line('select distinct(personal_id) from quiz_result') ;
     $res=[] ;
     if (_sizeof($personal_ids)) foreach($personal_ids as $personal_id)
     {   $data=execSQL('select * from quiz_result where personal_id='.$personal_id.' order by pkey') ;
         $lap=1 ;
         foreach($data as $rec)
         {   $question_id=$rec['question_id'] ;
             //if (isset($res[$lap][$question_id])) execSQL_update('update quiz_result set last=0 where personal_id='.$personal_id.' and lap=1 and question_id='.$question_id.' and pkey<'.$rec['pkey']) ;
             //else                                 execSQL_update('update quiz_result set last=1 where pkey='.$rec['pkey']) ;
             $res[$personal_id][$lap][$question_id][]=$rec['pkey'] ;
         }
     }
     $arr_last_0=[] ;
     $arr_last_1=[] ;
     if (_sizeof($res)) foreach($res as $personal_id=>$personal_recs)
        if (_sizeof($personal_recs)) foreach($personal_recs as $lap_id=>$lap_recs)
            if (_sizeof($lap_recs)) foreach($lap_recs as $question_id=>$answers_recs)
             { // имеем массив ответов на вопрос. Последний ответ должен получить last=1, остальные - last=0
               $last_indx=_sizeof($answers_recs)-1 ;
               $last_id=$answers_recs[_sizeof($answers_recs)-1] ;
               unset($answers_recs[$last_indx]) ;
               $prew_ids=(_sizeof($answers_recs))? implode(',',$answers_recs):'' ;
               if ($prew_ids) $arr_last_0[]=$prew_ids ;
               $arr_last_1[]=$last_id ;
             }
     //damp_array($res);
     //damp_array($arr_last_0);
     //damp_array($arr_last_1);
     echo 'Устанавливаем флаг last=0 для '._sizeof($arr_last_0).' результатов КЗ<br>' ;
     if (_sizeof($arr_last_0)) execSQL_update('update quiz_result set last=0 where pkey in ('.implode(',',$arr_last_0).')') ;
     echo 'Устанавливаем флаг last=1 для '._sizeof($arr_last_1).' результатов КЗ<br>' ;
     if (_sizeof($arr_last_0)) execSQL_update('update quiz_result set last=1 where pkey in ('.implode(',',$arr_last_1).')') ;
     //    $data=execSQL('select * from quiz_result where personal_id=18159 order by pkey',2) ;
 }



}

?>
