<?php
include_once(_DIR_EXT.'/HTML/c_page_TXT.php');
class c_services_quiz_result extends c_page_TXT
{

    function show(&$options=array())
    {
      ob_start() ;
      damp_array($_POST,1,-1) ;
      $quiz_session_id=$_POST['quiz_id'] ;
      $rec_session=execSQL_van('select * from quiz_sessions where pkey='.$quiz_session_id) ;
      // тест работы вопроса - поле personal_id пустое
      if ($rec_session['pkey'] and !$rec_session['personal_id'])
      { // удяляем тестовую сесиию - это мусор
        execSQL_update('delete from quiz_sessions where pkey='.$rec_session['pkey']) ;
        execSQL_update('delete from quiz_sessions_questions where parent='.$rec_session['pkey']) ;
      }
      else if ($rec_session['pkey'])
      {    update_rec_in_table('quiz_sessions',['status'=>2,'e_data'=>time()],'pkey='.$rec_session['pkey']) ;
          //damp_array($rec_session,1,-1) ;
          $question_ids=execSQL_line('select question_id from quiz_sessions_questions where parent='.$rec_session['pkey'].' and status=0 order by indx');
          // список ID корректных ответов
          $answer_correct=execSQL_row('select pkey,parent from quiz_answers where question_id in ('.implode(',',$question_ids).') and status=1 order by indx') ;
          $answer_correct2=execSQL('select pkey as id,parent,status from quiz_answers where question_id in ('.implode(',',$question_ids).') order by indx') ;
          $answer_correct22=[] ;
          if (_sizeof($answer_correct2)) foreach($answer_correct2 as $rec) $answer_correct22[$rec['parent']][$rec['id']]=$rec['status'] ;
          damp_array($answer_correct22);

          $data=array() ;
          $data['args']['data']['quiz']['answers']=[] ;
          if (_sizeof($answer_correct)) foreach($answer_correct as $answer_id=>$question_id)
          {
              $data['args']['data']['quiz']['answers'][]=['question_id'=>$question_id,'correct'=>(($_POST['quiz_answers'][$answer_id])? 1:0)] ;
          }
          damp_array($data,1,-1);

          		echo '<strong>Обработка данных QUIZ по событию examination_result_success</strong><br>' ;
          		{

          			// сохраняем данные измерений в запись сессии КЗ
          			/*$data_mo = array('e_data' => time(),
          	                     'reason' => '',
          	                     'equipment' => '',
          	                     'video' => '',
          							         'status'=>2
                                );
          			QUIZ()->update_quiz_session($quiz_session_id,$data_mo);
          			*/

          			$rec_quiz_sesson=QUIZ()->get_quiz_by_id($quiz_session_id) ;
          			$event_id=($rec_quiz_sesson['pass_id'])? execSQL_value('select event_id from obj_site_events_pass where pkey='.$rec_quiz_sesson['pass_id']):0 ;

          			// сбро
          			$arr_result = array();
          			if (_sizeof($data['args']['data']['quiz']['answers']))
          			{
          				foreach($data['args']['data']['quiz']['answers'] as $rec_answer) $arr_result[$rec_answer['question_id']] = 1;
          				foreach($data['args']['data']['quiz']['answers'] as $rec_answer) if (!$rec_answer['correct']) $arr_result[$rec_answer['question_id']] = 0;
          			}
          			?><strong>$arr_result</strong><?
          			damp_array($arr_result,1,-1);
          			//$event_id=execSQL_value('select event_id from obj_site_events_pass where pkey='.$quiz_session_id) ;
          			//foreach($arr_result as $question_id => $result2)
                execSQL_update('delete from quiz_result where quiz_id='.$quiz_session_id) ;

                foreach($answer_correct22 as $question_id => $arr_answers)
          			{	$theme_id = execSQL_value('select theme_id from quiz_questions where pkey=' . $question_id);
          			  $correct=0 ; $current_answer_id=0 ;
          			  foreach($arr_answers as $answer_id=>$anwer_correct)
                  {   // если этот ответ правильный и пришло с QUIZ что этот ответ выбран - ставим статус 1 - вопрос отвечен правильно
                      if ($anwer_correct and $_POST['quiz_answers'][$answer_id]) $correct=1 ;
                      if ($_POST['quiz_answers'][$answer_id]) $current_answer_id=$answer_id ;

                  }

          			  $data=array('clss' => 476,
                                  'indx' => 1,
                              'personal_id' => $rec_quiz_sesson['personal_id'],
                              'mo_id' => $rec_quiz_sesson['mo_id'],
                              'quiz_id' => $quiz_session_id,
                              'event_id' => $event_id,
                              'pass_id' => $rec_quiz_sesson['pass_id'],
                              'theme_id' => ($theme_id)? $theme_id:0,
                              'question_id' => $question_id,
                              'answer_id' => $current_answer_id,
                              'correct' => $correct,
                              'lap' => 1,
                              'last' => 1,

                            ) ;

          				$id=adding_rec_to_table('quiz_result',$data);
                        execSQL_update('update quiz_result set last=0 where personal_id='.$rec_quiz_sesson['personal_id'].' and lap=1 and question_id='.$question_id.' and pkey<'.$id) ;
                  QUIZ()->calculate_learned_by_result($id);
          				echo 'Добавлена запись в quiz_result: '.$id.'<br>' ;
          			}

          			// меняем статус участнику мероприятия
          			$rec_session=execSQL_van('select * from quiz_sessions where pkey='.$quiz_session_id,2) ;
          			if ($rec_session['pass_id'])
          			{   // тут необходима проверка на полному прохождения мероприятия
          			  $rec_event=EVENTS()->get_event_by_id($event_id) ;
          			  $pass_status=2 ;

          			  if ($rec_event['_ext_info']['close_status']==2 or $rec_event['_ext_info']['close_status']==3)
                  {   $themes_ids=$rec_event['_ext_info']['themes_ids'] ;  // $themes_ids=Array (4) ;
                      //1=>'В течении всего срока',2=>'Пока не будет задан каждый вопрос по одному разу',3=>'Пока не будет правильный ответ по одному разу'
                      // close_status=2: делаем запрос в базу на вопросы, которые еще не задавались сотруднику
                      // close_status=3: делаем запрос в базу на вопросы, на которые сотрудник еще ни разу правильно не отвечал
                      $usl_check=($rec_event['_ext_info']['close_status']==3)? 'and correct=1':'' ;

                      $now=getdate() ; $time_from=0 ;
                      switch($rec_event['_ext_info']['close_period'])
                      { case 2: $time_from=mktime(0,0,0,$now['mon'],1,$now['year']); break ; // c первого числа этого месяца
                        case 3: $time_from=mktime(0,0,0,$now['mon']-3,1,$now['year']); break ; // с первого числа три месяца назад
                        case 4: $time_from=mktime(0,0,0,1,1,$now['year']); break ; // с первого числа этого года
                        case 5: $time_from=mktime(0,0,0,$now['mon'],$now['mday'],$now['year']); break ;// с нуля часов сегодня
                        case 6: $time_from=mktime($now['hours'],0,0,$now['mon'],$now['mday'],$now['year']); break ;// с нуля минут сегодня текущий час
                        case 7: $time_from=mktime($now['hours'],$now['minutes'],0,$now['mon'],$now['mday'],$now['year']); break ;// с нуля секундт сегодня текущая минута
                      }
                      echo 'close_period='.QUIZ()->arr_events_close_period[$rec_event['_ext_info']['close_period']].'<br>' ;
                      echo '$time_from='.date('d.m.Y H:i',$time_from).'<br>' ;
                      $usl_time=($time_from)? ' and t2.c_data>='.$time_from:'' ;



                      if (_sizeof($themes_ids))
                      { $str_ids=implode(',',$themes_ids)	 ;
                        $recs_rasdels=execSQL_line('select pkey from quiz_themes where pkey in ('.$str_ids.') or parent1 in ('.$str_ids.') or parent2 in ('.$str_ids.')  or parent3 in ('.$str_ids.')  or parent4 in ('.$str_ids.')  or parent5 in ('.$str_ids.')  or parent6 in ('.$str_ids.')  or parent7 in ('.$str_ids.')  or parent8 in ('.$str_ids.') or parent9 in ('.$str_ids.')',0,1) ;
                        $recs_question=execSQL('select t1.* 
                                                from quiz_questions t1
                                                left join quiz_result t2 on t2.question_id=t1.pkey and t2.event_id='.$event_id.' and t2.personal_id='.$rec_quiz_sesson['personal_id'].$usl_check.$usl_time.'  
                                                where t1.parent in ('.implode(',',$recs_rasdels).') and t2.pkey is null  
                                              ',2) ;
                        if (!_sizeof($recs_question)) $pass_status=3 ;
                      }
                  }
          			  echo 'Статус участия в мероприятии: '.$pass_status.'<br>' ;
          				EVENTS()->set_event_personal_data_by_id($rec_session['pass_id'],array('status'=>$pass_status),'Пройден КЗ на терминале') ;
          			}

          		}


      }
      $text=ob_get_clean() ;
      LOGS()->reg_log('c_services_quiz_result','',['save_to_file'=>$text]) ;
    }
}
