<?php
include(_DIR_TO_MODULES.'/engine/i_backgroup_process.php') ;
class c_services_quiz_import_from_json extends i_backgroup_process_exec
{

  function exec()
  { $t1=fixed_time() ;  ob_start() ; $json_content='' ;
      $fdir=_DIR_TO_ROOT.$this->setting['json_fname'] ;
      $root_section_id=($this->setting['section_id'])? $this->setting['section_id']:1;
      if (!file_exists($fdir)) $fdir=_TEMP_DIR.$this->setting['json_fname'] ;
      if (file_exists($fdir))
      {
	      $json_content=file_get_contents($fdir) ;
     echo '<br>Размер файла <strong>'.show_size(strlen($json_content)).'</strong><br>' ;

      }
     if (strlen($json_content))
     {   $arr=json_decode($json_content,1) ;
         //damp_array($arr,1,-1) ;
         echo 'Тем: <strong>1</strong><br>' ;
         echo 'Разделов: <strong>'._sizeof($arr['sections']).'</strong><br>' ;
         echo 'Билетов: <strong>'._sizeof($arr['tikets']).'</strong><br>' ;
         echo 'Ответов: <strong>'._sizeof($arr['answers']).'</strong><br>' ;
         echo 'Файлов: <strong>'._sizeof($arr['contents']).'</strong><br>' ;
         FILE_LOG()->append('Тем: 1') ;
         FILE_LOG()->append('Разделов: '._sizeof($arr['sections'])) ;
         FILE_LOG()->append('Билетов: '._sizeof($arr['tikets'])) ;
         FILE_LOG()->append('Ответов: '._sizeof($arr['answers'])) ;
         FILE_LOG()->append('Файлов: '._sizeof($arr['contents'])) ;


         $arr_section_ids=array() ;  $arr_tiket_ids=array() ;
         $rec_thema=$arr['thema'] ;
         $arr_section_ids[$rec_thema['id']]=QUIZ()->section_create(array('name'=>$rec_thema['name'],'parent'=>$root_section_id)) ;
         echo 'Добавлена тема: ID <strong>'.$arr_section_ids[$rec_thema['id']].'</strong><br>' ;
         FILE_LOG()->append('Добавлена тема: ID '.$arr_section_ids[$rec_thema['id']]) ;

         $i=1 ;  $i_max=_sizeof($arr['sections']) ; $arr_sections_json_data=[] ;
         if (_sizeof($arr['sections'])) foreach($arr['sections'] as $old_section_id=>$rec_section)
         {

            $new_section_id=QUIZ()->section_create(array('name'=>$rec_section['name'],'parent'=>$arr_section_ids[$rec_section['parent']],'manual'=>$rec_section['manual'],'json_data'=>$rec_section['json_data'])) ;
            $arr_section_ids[$old_section_id]=$new_section_id ;
            $arr_sections_json_data[$new_section_id]=$rec_section['json_data'] ;
            echo 'Добавлен раздел: ID <strong>'.$new_section_id.'</strong><br>' ;
            FILE_LOG()->append('Добавлен раздел: ID '.$new_section_id.' ('.$i.' из '.$i_max.')') ;
            $i++ ;
         }

         $i=1 ;  $i_max=_sizeof($arr['known']) ;
         if (_sizeof($arr['known'])) foreach($arr['known'] as $old_known_id=>$rec_known)
         {  $old_section_id=$rec_known['parent'] ;
            $new_section_id=$arr_section_ids[$old_section_id] ;
            $new_known_id=QUIZ()->known_create($new_section_id,array('name'=>$rec_known['name'],'section_id'=>$new_section_id,'manual'=>$rec_known['manual'],'json_data'=>$rec_known['json_data'])) ;
            $arr_section_ids[$old_known_id]=$new_known_id ;
            echo 'Добавлено знание: ID <strong>'.$new_known_id.'</strong><br>' ;
            FILE_LOG()->append('Добавлено знание: ID '.$new_known_id.' ('.$i.' из '.$i_max.')') ;
            $i++ ;
         }


       // после импорта всех знаний надо заменить ID знаний в JSON документа на новые
       //if (_sizeof($arr_sections_json_data)) foreach($arr_sections_json_data)

         //damp_array($arr_sections_json_data,1,-1);
         if (_sizeof($arr_sections_json_data)) foreach($arr_sections_json_data as $id=>$json_data)
         {
             $this->replace_kbarticle($arr_section_ids,$json_data) ;
             QUIZ()->section_save($id,['json_data'=>$json_data]);
         }




	     //TREE('quiz_themes')->update_levels_parents('1',array('debug'=>1)) ;
         //damp_array($arr_section_ids,1,-1);
	     FILE_LOG()->append('Проставлены уровни каталога') ;

	     $i=1 ;  $i_max=_sizeof($arr['tikets']) ;
         if (_sizeof($arr['tikets'])) foreach($arr['tikets'] as $old_tiket_id=>$rec_tiket)
         {  $old_section_id=$rec_tiket['section_id'] ;
            $new_section_id=$arr_section_ids[$old_section_id] ;
            $new_tiket_id=QUIZ()->question_create($new_section_id,array('obj_name'=>$rec_tiket['text'],'timeout'=>$rec_tiket['timeout'])) ;
            $arr_tiket_ids[$old_tiket_id]=$new_tiket_id ;
            echo 'Добавлен билет: ID <strong>'.$new_tiket_id.'</strong><br>' ;
            FILE_LOG()->append('Добавлен билет: ID '.$new_tiket_id.' ('.$i.' из '.$i_max.')') ;
	        $i++ ;
         }

	     $i=1 ;  $i_max=_sizeof($arr['answers']) ;
         if (_sizeof($arr['answers'])) foreach($arr['answers'] as $rec_answer)
         {  $old_tiket_id=$rec_answer['tiket_id'] ;
            $answers_id=QUIZ()->answers_create($arr_tiket_ids[$old_tiket_id],array('indx'=>$rec_answer['indx'],'obj_name'=>$rec_answer['text'],'status'=>$rec_answer['status'])) ;
            echo 'Добавлен ответ: ID <strong>'.$answers_id.'</strong><br>' ;
            FILE_LOG()->append('Добавлен ответ: ID '.$answers_id.' ('.$i.' из '.$i_max.')') ;
	        $i++ ;
         }

	     $i=1 ;  $i_max=_sizeof($arr['contents']) ;
         if (_sizeof($arr['contents'])) foreach($arr['contents'] as $rec_content)
         {   $file_content=base64_decode($rec_content['data']) ;
             $temp_name=$rec_content['name'] ;
             $tiket_id=$arr_tiket_ids[$rec_content['tiket_id']] ;
             file_put_contents(_TEMP_DIR.$temp_name,$file_content) ;
             echo 'Сохранен временный файл <strong>'.$temp_name.'</strong>, размер <strong>'.show_size(strlen($file_content)).'</strong><br>' ;
             $content_id=QUIZ()->tiket_content_create($tiket_id,$temp_name) ;
             echo 'Добавлен контент ответа: ID <strong>'.$content_id.'</strong><br>' ;
             FILE_LOG()->append('Добавлен контент ответа: ID '.$content_id.' ('.$i.' из '.$i_max.')') ;
	         $i++ ;
         }
    }
     else echo 'Файл не найден: <strong>'.hide_server_dir($fdir).'</strong><br>' ;

    FILE_LOG()->append('END') ;
    $text=ENGINE()->get_html_doc_content(ob_get_flush()) ;


    $trace_fname='import_trace_'.$this->session_uid.'.html' ;
 	LOGS()->reg_file_log($trace_fname,$text,array('no_append_time'=>1)) ;

    $t2=fixed_time($t1) ;
    LOGS()->reg_log('quiz_import_from_json','<a target=_blank href="'.$this->page_output.'">Отчет</a><br><a href="/temp/full_'.basename($this->log_fname).'" target=_blank>Лог загрузки</a><br><a href="'.$this->log_bash.'" target=_blank>Лог BASH</a>',array('time_exec'=>$t2)) ;

  }

  function replace_kbarticle($arr_section_ids,&$json_data)
  {
      if (_sizeof($json_data['children'])) foreach($json_data['children'] as $id=>$child)
      {
          if (isset($child['attributes']['kbarticle']))
          {
              $value=$child['attributes']['kbarticle'] ;
              $old_known_id=str_replace('kbarticle:','',$value) ;
              echo '$old_known_id='.$old_known_id.'<br>' ;
              $new_known_id=$arr_section_ids[$old_known_id] ;
              echo '$new_known_id='.$new_known_id.'<br>' ;
              $json_data['children'][$id]['attributes']['kbarticle']='kbarticle:'.$new_known_id ;


          }
          if (_sizeof($json_data['children'][$id]['children'])) $this->replace_kbarticle($arr_section_ids,$json_data['children'][$id]) ;
      }
  }
}



?>
