<?

class c_services_quiz_operation
{
    function show()
    {
        $data=$this->prepare_data();
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
    }

    function prepare_data()
    {
        $t1=fixed_time();
        $rec_quiz=array();
        ob_start();
        //$ids=explode(',',$_GET['id']) ;  $result=array()
        // передаем ID записи сесиии QUIZ из таблицы quiz_sessions
        $quiz_id=(int)$_GET['id'];
        $result=array();
        if($quiz_id) $rec_quiz=QUIZ()->get_quiz_by_id($quiz_id);

        //damp_array($rec_quiz);

        if($rec_quiz['pkey'])
        {

            //$main_event_pass=$ids[array_rand($ids)];
            $rec_event_pass=execSQL_van('select * from obj_site_events_pass where pkey='.$rec_quiz['pass_id']);

            //if (!$rec_event_pass['pkey']) return(array('error'=>'event pass #'.$main_event_pass.' not found')) ;
            $rec_event=EVENTS()->get_event_by_id($rec_event_pass['event_id']);
            if(!$rec_event_pass['pkey']) return (array('error'=>'event ID '.$rec_event_pass['event_id'].' not found'));
            //damp_array($rec_event_pass) ;

            // вопросы, которые которые будут заданы, уже подготовлены

                $result['quiz']=array();
                $result['quiz']['id']=(string)$quiz_id;
                $result['quiz']['title']=$rec_event['obj_name']; //$theme_full_name ;
                $result['quiz']['min_questions']=(int)$GLOBALS['LS_quiz_question_count'];
                $result['quiz']['max_errors']=(int)$GLOBALS['LS_quiz_question_count'];
                if($GLOBALS['LS_quiz_timeout_enable']) $result['quiz']['correct_answer_timeout']=(int)$GLOBALS['LS_quiz_correct_answer_timeout'];
                if($GLOBALS['LS_quiz_timeout_enable']) $result['quiz']['incorrect_answer_timeout']=(int)$GLOBALS['LS_quiz_incorrect_answer_timeout'];

                $recs_question=array();
                //  если передан конкретный список вопросов - выбираем его
                if($_GET['q']) $recs_question=execSQL('select * from quiz_questions where pkey in ('.$_GET['q'].') limit '.$GLOBALS['LS_quiz_question_count'],1);
                elseif($rec_quiz['quiestion_ids']) $recs_question=execSQL('select * from quiz_questions where pkey in ('.$rec_quiz['quiestion_ids'].') limit '.$GLOBALS['LS_quiz_question_count'],1);

                if(_sizeof($recs_question))
                {
                    $recs_answers=execSQL('select * from quiz_answers where question_id in ('.implode(',',array_keys($recs_question)).')',1);
                    $recs_contents=execSQL('select * from quiz_content where question_id in ('.implode(',',array_keys($recs_question)).')',1);
                    $recs_answers_by_question=group_by_field('question_id',$recs_answers);
                    $recs_contents_by_question=group_by_field('question_id',$recs_contents);
                    foreach($recs_question as $rec_question)
                    {
                        $data_question=array('id'=>$rec_question['pkey'],'text'=>mb_str_replace(["\t","\n","\r"],"",$rec_question['obj_name'].' ['.$rec_question['pkey'].']'),'images'=>array(),'video'=>array(),'answers'=>array());
                        if($GLOBALS['LS_quiz_timeout_enable'])
                        {
                            if($rec_question['timeout']) $data_question['timeout']=(int)$rec_question['timeout'];
                            else $data_question['timeout']=(int)$GLOBALS['LS_quiz_answer_timeout'];
                        }

                        if(_sizeof($recs_contents_by_question[$rec_question['pkey']])) foreach($recs_contents_by_question[$rec_question['pkey']] as $rec_content)
                        {
                            if(file_exists(_DIR_TO_ROOT.$rec_content['dir'].$rec_content['file_name']))
                            {
                                $content=file_get_contents(_DIR_TO_ROOT.$rec_content['dir'].$rec_content['file_name']);
                                $data_question['images'][]='data:'.$rec_content['type'].';base64,'.base64_encode($content);
                            }
                        }

                        if(_sizeof($recs_answers_by_question[$rec_question['pkey']])) foreach($recs_answers_by_question[$rec_question['pkey']] as $rec_answer)
                        {
                            $data_answer=array('id'=>$rec_answer['pkey'],'text'=>mb_str_replace(["\t","\n","\r"],"",$rec_answer['obj_name']),'correct'=>($rec_answer['status'])? true:false);
                            $data_question['answers'][]=$data_answer;
                        }

                        $result['quiz']['questions'][]=$data_question;
                    }
                }
                $result['quiz']['min_questions']=_sizeof($result['quiz']['questions']) ;
		            $result['quiz']['max_errors']=_sizeof($result['quiz']['questions']) ;

        }
        else $result['error']='incorrect quiz_id ['.$quiz_id.']';
        $debug=ob_get_clean();
        //echo $debug ;
        $t2=fixed_time($t1);
        //LOGS()->reg_log('c_services_quiz_operation',$debug) ;
        //damp_array($result,1,-1) ;
        LOG_JSON('mo_session')->reg('services quiz content',$debug);
        $log_fname=($rec_quiz['mo_id'])? 'mo_trace_'.$rec_quiz['mo_id']:'mo_trace_'.$rec_quiz['pkey'];
        LOG_JSON('mo_session')->flush($log_fname,array('reg_log'=>1,'comment'=>'Подгрузка контента QUIZ на терминал [/services/quiz/operation/]'));

        if($GLOBALS['LS_trace_term'])
        {
            $text_json_out=(is_array($result) and _sizeof($result))? json_encode($result,JSON_UNESCAPED_UNICODE):'';
            LOGS()->log_request($_SERVER['REMOTE_ADDR'],$_SERVER['SERVER_ADDR'],'quiz','',$text_json_out,array('terminal_id'=>0,'personal_id'=>$rec_event_pass['personal_id'],'mo_id'=>$rec_quiz['mo_id'],'size1'=>0,'size2'=>strlen($text_json_out),'time_exec'=>$t2,'request_UID'=>0,'request_debug'=>$debug,'req_type'=>0,'req_url'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_ADDR'].$_SERVER['REQUEST_URI']));
        }

        return ($result);
    }
}

?>
