    <?php
    include_once(_DIR_EXT.'/HTML/c_page_TXT.php');
class c_services_quiz_frame extends c_page_TXT
{
    public $content_view_id=0;
    public $is_vurtual_term=0;
    public $check_icon='<i class="fas fa-check"></i>';

    public function __construct()
    {
        $this->content_view_id=_CUR_ID;

    }

    function show()
    { ob_start();
        // данные
        //$rec_content_view=execSQL_van('select * from media_content_view where pkey='.$this->content_view_id);
        //if ($rec_content_view['pkey'])
        {   // определяем откуда пришел запрос на контент - если виртуальный терминал - то видеo надо запускать сразу
        $arr_refferer=parse_url($_SERVER['HTTP_REFERER']);
        $this->is_vurtual_term=($arr_refferer['host']==_MAIN_DOMAIN)? 1:0;

        //LOG_JSON('event_pass')->reg('get_media_content','Получен запрос на медиаконтент ID '.$this->content_view_id);

        ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title>ЭСМО</title>
            <link rel="stylesheet" type="text/css" href="<?echo _PATH_TO_EXT?>/interface/bootstrap-4.4.1/css/bootstrap.css" charset="utf-8">
           	<link rel="stylesheet" type="text/css" href="<?echo _PATH_TO_EXT?>/interface/bootstrap-4.4.1/jBootstrap.css" charset="utf-8">
            <link rel="stylesheet" type="text/css" href="/AddOns/font-awesome-4.7.1/css/font-awesome.css" charset="utf-8">
           	<link rel="stylesheet" type="text/css" href="/AddOns/fontawesome-free-5.12.0/css/all.css" charset="utf-8">

            <SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/jquery/jquery-3.4.1.min.js"></SCRIPT>
            <SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/jquery/jquery.timers-1.2.js"></SCRIPT>
            <SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/bootstrap-4.4.1/js/bootstrap.js" ></SCRIPT>
           	<SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/bootstrap-4.4.1/jBootstrap.js" ></SCRIPT>
           	<SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/bootstrap-4.4.1/ajax.bootstrap.js" ></SCRIPT>
           	<SCRIPT type="text/javascript" src="<?echo _PATH_TO_EXT?>/jquery/jquery.form.min.js" ></SCRIPT>

            <link rel="stylesheet" type="text/css" href="<?echo _PATH_TO_EXT?>/interface/jQuery-Countdown-Timer-Digital-Clock-Plugin-timeTo/timeTo.css" charset="utf-8">
            <script src="<?echo _PATH_TO_EXT?>/interface/jQuery-Countdown-Timer-Digital-Clock-Plugin-timeTo/jquery.time-to.js" defer></script>

            <script type="text/javascript">let server_url = "<?echo _PATH_TO_SITE?>";</script>
            <style type="text/css">
                body{width:1024px;height:700px;margin:0 auto;position:relative;}
                div.current_time {text-align: center;font-size: 18px;color: black;}
                div.content {text-align: center;font-size: 18px;color: black;}

                div#the_end {text-align: center;padding-top:180px;display:none;}
                div#the_end div.icon{color:green;font-size:30px;height:100px;}
                div#the_end div.icon i{margin-top:30px;}
                div#the_end div.status{font-size:18px;color:#272727;}

                table.table_text {width: 100%;height: 100%;}
                table.table_text td {text-align: center;vertical-align: center;font-size: 22px;color: #272727;}


                div.tiket{padding-top:23px;}
                div.tiket.hidden{display:none;}
                div.tiket table.inner{width: 95%;margin: 30px auto 0 auto;height:400px;}

                div.tiket table.inner td.col{vertical-align:middle;text-align:center;}
                div.tiket table.inner td.col.col_content{width:500px;border:1px solid #aaaaaa;}
                div.tiket table.inner td.col.col_question{width:auto;}

                div.tiket div.title {font-weight: bold;}
                div.tiket div.cnt_info {position:absolute;bottom:20px;left:20px;font-size:30px;}
                div#countdown {position:absolute;bottom:20px;left:440px;}
                div.tiket i.next_question {font-size:4em;position:absolute;bottom:20px;right:20px;cursor: pointer;}

                /*div.tiket table.table_image {width: 500px;height: 300px;border:1px solid #aaaaaa;margin:0 auto 20px auto;}
                div.tiket table.table_image td {text-align: center;vertical-align: center;font-size: 22px;color: #272727;}
                div.tiket table.table_image td img {max-width: 100%;max-height: 1000px;}*/


                div.tiket table.answer{width:100%;min-height:80px;margin:10px 0;border-bottom:1px solid #aaaaaa;}
                div.tiket table.answer td{vertical-align:middle;min-height:100px;text-align:left;padding:10px;font-size:16px;}
                div.tiket table.answer:last-child{border-bottom:none;}
                div.tiket table.answer.selected td{font-weight:bold;}
                div.tiket.show_only_correct table.answer.correct{background-color:#aacc99}
                div.tiket.show_correct table.answer.correct{background-color:#aacc99}
                div.tiket.show_correct table.answer.uncorrect{background-color:#CB5B5E;}
                div.tiket table.inner.no_content td{font-size:22px;}

                div.alert{margin-top:100px;padding-top:100px;}
                table.by_center{width:100%;height:100%;}
                table.by_center td{vertical-align:middle;text-align:center;padding-top:200px;}
            </style>
        </head>
        <body class="shadow"><form id=form method="post">
        <div class="content">
            <input type="hidden" name="quiz_id" value="<? echo _CUR_ID ?>">
            <div id="countdown"></div>
            <?

            //$res_quiz=$this->prepare_data(_CUR_ID);
            $rec_session=QUIZ()->get_quiz_by_id(_CUR_ID) ;
            if ($rec_session['pkey'] and $rec_session['status']<=1)
            {   $now=getdate() ;
                $data['status']=1 ;
                $data['c_data']=time() ;
                $data['c_data_m']=mktime($now['hours'],$now['minutes'],0,$now['mon'],$now['mday'],$now['year']) ;
                $data['c_data_h']=mktime($now['hours'],0,0,$now['mon'],$now['mday'],$now['year']) ;
                $data['c_data_d']=mktime(0,0,0,$now['mon'],$now['mday'],$now['year']) ;

                update_rec_in_table('quiz_sessions',$data,'pkey='.$rec_session['pkey']) ;
                $question_ids=execSQL_line('select question_id from quiz_sessions_questions where parent='.$rec_session['pkey'].' and status=0 order by rand()');
                $recs_question=QUIZ()->get_questions_by_ids(implode(',',$question_ids)) ;
                $recs_aswers=QUIZ()->get_answers_by_question_id(implode(',',$question_ids),['order'=>'rand()']) ;
                $recs_contents=QUIZ()->get_contents_by_question_id(implode(',',$question_ids)) ;

                $recs_aswers_by_questions=group_by_field('question_id',$recs_aswers) ;
                $recs_contents_by_questions=group_by_field('question_id',$recs_contents) ;

                if(_sizeof($recs_question)) foreach($recs_question as $i=>$rec_question)
                { ?><div id=tiket_<?echo $i+1?> <?if (($i+1)<_sizeof($recs_question)) {?>next_tiket="tiket_<?echo $i+2?>"<?}?> class="tiket <?if (!$i) echo 'current'?> <?if ($i) echo 'hidden'?>">
                        <div class="question"><h1 class="display-4" style="font-size:2em;"><? echo $rec_question['obj_name'] ?></h1></div>
                        <div class="cnt_info"><?echo $i+1?> из <?echo _sizeof($question_ids)?></div>
                        <!--<i class="fas fa-chevron-circle-right text-success next_question"></i>-->
                        <? if (_sizeof($recs_contents_by_questions[$rec_question['pkey']][0])){?>
                    <table class="inner">
                        <tr>
                            <td class="col col_content"><?$this->panel_content($recs_contents_by_questions[$rec_question['pkey']][0])?></td>
                            <td class="col col_question"><?$this->panel_answers($recs_aswers_by_questions[$rec_question['pkey']])?></td>
                        </tr>
                        </table><?}
                        else
                            {
                                ?><table class="inner no_content">
                                    <tr>
                                        <td class="col col_question"><?$this->panel_answers($recs_aswers_by_questions[$rec_question['pkey']])?></td>
                                    </tr>
                                </table><?

                            }

                        ?>
                 </div><?
                }
                ?><div id="the_end"><h1 class="display-4" style="font-size:2em;">Контроль знаний завершен</h1>
                    <div class="icon">
                        <div class="spinner-border m-5" role="status">
                          <span class="sr-only">Loading...</span>
                        </div>
                    </div>
                    <div class="status">Идет сохранение результатов...</div>
                </div><?



            ?><script type="text/javascript">
                        // Сообщение терминалу что страница готова.
                        $j(document).ready(function ()
                        {
                           function show_correct_and_go_next_tiket(question_is_correct)
                           {   // останавливаем таймер
                               $j('#countdown').timeTo('stop');

                               var tiket=$j('div.tiket.current') ;
                               // показываем правильный ответ, также это будет блокировать клик по ответу
                               // добавлено - при клике на правильный ответ не подсвечивать неправилные ответы
                               var pause=1 ;
                               if (!question_is_correct) { $j(tiket).addClass('show_correct') ;  pause="<?echo $GLOBALS['LS_quiz_incorrect_answer_timeout']?>s" ; }
                               else                      { $j(tiket).addClass('show_only_correct') ; pause="<?echo $GLOBALS['LS_quiz_correct_answer_timeout']?>s" ; }
                               // через 2 сек


                               $j(tiket).oneTime(pause, function()
                               {
                                  // добаляем анимацию
                                  $j(tiket).fadeOut(500,function(){



                                      // скрываем текущую панель
                                      $j(tiket).hide().removeClass('current') ;

                                      if ($j(tiket).attr('next_tiket'))
                                      { // показываем слудующую панель
                                        $j('div#'+$j(tiket).attr('next_tiket')).show().addClass('current') ;
                                        // запускаем повторно таймер
                                        start_timer() ;
                                      }
                                      else
                                      {
                                          // скрываем текущую панель
                                          $j('div#the_end').show() ;
                                          $j('div#countdown').hide() ;

                                          var options = {
                                                  url:       '<?echo _PATH_TO_SITE?>/services/quiz/result/',         // override for form's 'action' attribute
                                                  type:      'post',        // 'get' or 'post', override for form's 'method' attribute
                                                  //dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
                                                  clearForm: true,        // clear all form fields after successful submit
                                                  resetForm: true,        // reset the form after successful submit
                                                  success:    function() {
                                                                            $j('div#the_end div.icon').html('<?echo $this->check_icon?>') ;
                                                                            $j('div#the_end div.status').html('Результаты сохранены') ;
                                                                            console.log('ajaxSuccess') ;

                                                                            <?if ($rec_session['personal_id']){?>get_personal_quiz_stats() ;<?}?>



                                                                         },
                                                  // $.ajax options can be used here too, for example:
                                                  //timeout:   3000
                                              };

                                          $j('#form').ajaxSubmit(options);
                                          console.log('ajaxSubmit') ;
                                      }
                                  });


                               }) ;
                           }

                           function get_personal_quiz_stats()
                           {
                               var options = {   url:       '<?echo _PATH_TO_SITE?>/services/quiz/stats/',         // override for form's 'action' attribute
                                                 type:      'post',        // 'get' or 'post', override for form's 'method' attribute
                                                 clearForm: true,        // clear all form fields after successful submit
                                                 resetForm: true,        // reset the form after successful submit
                                                 success:    function(data) { //console.log(data) ;
                                                                              if (data) $j('div.content').html(data) ;
                                                                           //$j('div#the_end div.status').html('Результаты сохранены') ;
                                                                           //console.log('ajaxSuccess') ;

                                                                           //get_personal_quiz_stats() ;



                                                                        },
                                                 // $.ajax options can be used here too, for example:
                                                 //timeout:   3000
                                             };

                                         $j('#form').ajaxSubmit(options);
                                         console.log('ajaxSubmit') ;
                           }

                           function fix_question_status(el)
                           {   if ($j('div.tiket.current').hasClass('show_correct')) return ;
                               if ($j('div.tiket.current').hasClass('show_only_correct')) return ;
                               $j(el).find('input').val(1) ; // помечаем выбранный ответ
                           }

                           function start_timer()
                           {
                               $j('#countdown').timeTo({ seconds:<?echo $GLOBALS['LS_quiz_answer_timeout']?>,
                                                         countdown: true,
                                                         callback: show_correct_and_go_next_tiket
                                                       });
                           }

                           // клик по кнопке далее
                           $j('i.next_question').on('click',show_correct_and_go_next_tiket) ;

                           // клик по ответу на вопрос
                           $j('table.answer').on('click',function()
                           {  $j(this).addClass('selected') ;

                               fix_question_status(this) ;
                               show_correct_and_go_next_tiket($j(this).hasClass('correct'))
                           }) ;

                           // таймер на время ответа
                           start_timer() ;
                        });
                </script>
              <?
            }
            else if ($rec_session['status']>1)
            {
                ?>
                <table class="by_center"><tr><td>
                                        <strong>Сессия контроля знаний ID <?echo $rec_session['pkey']?> уже завершена.</strong><br>
                                        <small>Контроль знаний пройден <?echo date('d.m.Y H:i',$rec_session['c_data'])?></small>
                                    </td></tr>
                                  </table>
                <?
                //if ($rec_session['pkey']==524) execSQL_update('update quiz_sessions set status=0 where pkey=524') ;
            }
            else
            {
                ?>
                <table class="by_center"><tr><td>
                                        <strong>Сессия контроля знаний ID <?echo _CUR_ID?> не найдена</strong><br>
                                        <small></small>
                                    </td></tr>
                                  </table>
                <?
            }


            //$rec_content=execSQL_van('select * from media_content where pkey='.$rec_content_view['content_id']) ;
            //echo $rec_content['file_name'] ;
            ?></div></form>
        </body>
        <script type="text/javascript" src="<? echo _PATH_TO_SITE ?>/<? echo _CLASS_ ?>/ext/events_media/terminal-ipc.js?rand=<? echo rand(1,1000000) ?>"></script>

        <script type="text/javascript">
            // Сообщение терминалу что страница готова.
            $j(document).ready(function () {
                sendAppEvent('media-content-ready');
            });
        </script>
        </html>

        <?

        //LOG_JSON('event_pass')->reg('get_media_content','Сформирован медиаконтент <strong>'.$rec_content['type'].'</strong>: <strong>'.$rec_content['file_name'].'</strong> <strong>'.$rec_content['manual'].'</strong><br>');
        //LOG_JSON('event_pass')->flush('event_pass_'.$rec_content_view['pass_id']);
        //damp_array($rec_session);
        }
    $text=ob_get_clean();
    echo $text;
    //LOGS()->reg_log('$rec_content_view',$text);
    }

    function panel_content($rec_content)
    {
        if ($rec_content['pkey'])
        { //if ($rec_content['type']=='text'){$this->show_text($rec_content);}
          if (strpos($rec_content['type'],'image')!==false){$this->show_image($rec_content);}
          //if (strpos($rec_content['type'],'video')!==false)  $this->player_code_avi($rec_content['file_name'],array('pass_id'=>$rec_content_view['pass_id'],'content_id'=>$rec_content_view['content_id'],'content_view_id'=>$this->content_view_id)) ;
        }
    }

    function panel_answers($recs_aswers)
    {//print_2x_arr($recs_aswers);
        if(_sizeof($recs_aswers)) foreach($recs_aswers as $answer)
            {   ?>
                <table class="answer <?echo ($answer['status'])? 'correct':'uncorrect' ?>"><tr><td>
                <input type="hidden" name="quiz_answers[<? echo $answer['pkey'] ?>]" value="0">
                <? echo $answer['obj_name'] ?>
                </td></tr></table><?
                //$i++;
            }
    }


    /*function show_text($rec_content,$rec_content_view)
    {
        if(!$rec_content_view['length']) $rec_content_view['length']=10;
        ?>
        <table class="table_text">
        <tr>
            <td style="font-size:24px;"><? echo $rec_content['manual']; ?></td>
        </tr></table><?
        $this->show_JS_timer_mediacontenthidden($rec_content_view);
    }*/

    /*function show_JS_timer_mediacontenthidden($rec_content_view)
    { ?>
        <script type="text/javascript">
            $j(document).ready(function () {
                $j('body').oneTime('<?echo $rec_content_view['length']?>s','mediacontenthidden',function () {
                    console.log('image show ended');
                    var data = {
                        event: 'media-content-hidden',payload: {
                            pass_id:<?echo $rec_content_view['pass_id']?>,
                            media_id:<?echo $rec_content_view['content_id']?>,
                            content_view_id:<?echo $rec_content_view['pkey']?>,
                        }
                    };
                    var server_url = "<?echo _PATH_TO_SITE?>";
                    $j.ajax({
                                url: server_url+'/services/events_media/reg_event/',
                                type: 'POST',
                                dataType: 'xml',
                                cache: false,
                                data: data
                            });
                    //sendAppEvent('media-content-done')
                })
            });
        </script>
        <?
    }
    */

    function show_image($rec_content,$rec_content_view=[])
    {
        //if(!$rec_content_view['length']) $rec_content_view['length']=10;
        ?><img src="<? echo _PATH_TO_SITE.$rec_content['dir'].$rec_content['file_name'] ?>"><?
        //$this->show_JS_timer_mediacontenthidden($rec_content_view);
    }

    /*
    function player_code_avi($video_url,$options=array())
    {
        $_style=array();
        $_style[]='max-width:100%';
        $_style[]='max-height:100%';
        if($options['video_rotare']) $_style[]='transform:rotate('.$options['video_rotare'].'deg)';

        ?>
        <video id=terminal_media style="<? echo implode(';',$_style) ?>">
            <source src="<? echo $video_url ?>">
        </video>
        <script type="text/javascript">
            var videoEl = document.getElementsByTagName('video')[0];

            function start() { videoEl.play(); }

            function stop() { videoEl.pause(); }

            // обработываем событие окончания показа видео
            videoEl.addEventListener("ended",function () {
                console.log('video ended');
                sendAppEvent('media-content-done')
                $j.ajax({
                            url: server_url+'/services/events_media/reg_event/',
                            type: 'POST',
                            dataType: 'xml',
                            cache: false,
                            data: {
                                event: 'media-content-hidden',payload: {
                                    pass_id:<?echo $options['pass_id']?>,
                                    media_id:<?echo $options['content_id']?>,
                                    content_view_id:<?echo $options['content_view_id']?>,
                                }
                            }
                        });
            },true);
            //v.currentTime = 10.0;
            <?if ($this->is_vurtual_term) {?>start();<?}?>
        </script>
        <style type="text/css">
            video#terminal_media
            {
                position:  fixed; right: 0; bottom: 0;
                min-width: 100%; min-height: 100%;
                width:     auto; height: auto; z-index: -100;
            }
        </style>

        <?
    }
    */
}
