<?php

$__functions['init'][]='_media_content_site_vars' ;
$__functions['boot_site'][]='_media_content_site_boot' ;

function MEDIA_CONTENT() {
  if (isset($_SESSION['media_content_system'])) {
    return($_SESSION['media_content_system']);
  } else {
    $_SESSION['media_content_system']=new c_media_content_system();
    return($_SESSION['media_content_system']);
  }
}


function _media_content_site_vars()
{
    $_SESSION['init_options']['media_content']['debug']=0 ;
}

function _media_content_site_boot($options)
{
  create_system_modul_obj('media_content',$options) ;

}


class c_media_content_system
{

    function __construct($create_options=array())
    {
	    ENGINE()->reg_ext('events_media_content','Медиа-контент')  ;
    }


	function get_theme_by_id($id)
	{
	  $rec=execSQL_van('select * from media_content_themes where pkey='.$id) ;
	  return($rec) ;
	}

	function get_tiket_by_id($id)
	{
	  $rec=execSQL_van('select * from media_content_questions where pkey='.$id) ;
	  return($rec) ;
	}

	function get_question_by_id($id)
	{
	  $rec=execSQL_van('select * from media_content_questions where pkey='.$id) ;
	  return($rec) ;
	}

	function get_answers_by_question_id($id)
    {
        $rec=execSQL('select * from media_content_answers where question_id='.$id.' order by indx') ;
        return($rec) ;
    }

	function get_contents_by_question_id($id)
    {
        $rec=execSQL('select * from media_content_content where question_id='.$id.' order by indx') ;
        return($rec) ;
    }

	function section_create($data)
	 { $rec['clss']=472 ;
	   $rec['parent']=$data['parent'] ;
	   $rec['obj_name']=$data['name'] ;
	   $reffer=adding_rec_to_table('media_content_themes',$rec) ;
	   LOGS()->reg_log('media_content_edit','Добавлена новая тема/раздел :'.$rec['obj_name'].', в раздел ID: '.$rec['parent'],array('reffer'=>$reffer)) ;
	   return($reffer) ;
	 }

	function section_save($id,$data)
	 { $rec['obj_name']=$data['name'] ;
	   $reffer=update_rec_in_table('media_content_themes',$rec,'pkey='.$id) ;
	   //LOGS()->reg_log('media_content_edit','Из новая тема/раздел :'.$rec['obj_name'].', в раздел ID: '.$rec['parent'],array('reffer'=>$reffer)) ;
	   return($reffer) ;
	 }

	function question_create($media_content_id,$rec)
	 { $rec['clss']=473 ;
	   //$rec['account_id']=MEMBER()->id ;
	   //$rec['c_data']=ti ;
	   $rec['parent']=$media_content_id ;
	   $rec['event_id']=$media_content_id ;
       //$theme_id=execSQL_value('select parent2 from media_content_themes where pkey='.$parent_id) ;
	   //$rec['theme_id']=$theme_id ;
	   //$rec['obj_name']=$question_text ;
	   //$rec['comment']=$data['comment'] ;
		 //damp_array($rec,1,-1) ;
	   $id=adding_rec_to_table('media_content_questions',$rec) ;
	   return($id) ;
	 }
	function answers_create($question_id,$rec)
	 { $rec['clss']=474 ;
	   //$rec['account_id']=MEMBER()->id ;
	   //$rec['c_data']=ti ;
	   $rec['parent']=$question_id ;
	   $rec['question_id']=$question_id ;
	   //$rec['obj_name']=$answers_text ;
	   //$rec['status']=($answers_status)? 1:0 ;
	   $id=adding_rec_to_table('media_content_answers',$rec) ;
	   return($id) ;
	 }


    // возвращает в массиве размер и тип файла $file_dir
    // если передан параметр $show_info=1, выводится сообщение данными

    function get_small_file_info($file_dir,$options=array())
    {  $size_info=filesize($file_dir) ;
       if ($options['view_upload']) echo 'Размер файла <span class=green>'.format_size($size_info).'</span>' ;
       $file_type=mime_content_type($file_dir) ;
       if ($options['view_upload']) {if ($file_type) echo ', формат файла: <span class="black bold">'.$file_type.'</span><br>' ; else echo '<br>' ;}
       return(array($size_info,$file_type)) ;
    }

    // фото/видео билета храниться в директориях по номеру раздела билета, имя файла - начинается с  ID билета
	 function tiket_content_create($tiket_id,$fname)
	 { $parent=execSQL_value('select parent from media_content_questions where pkey='.$tiket_id) ;
	   $source_fname=_TEMP_DIR.$fname ;
	   $target_dir=_DIR_TO_ROOT.'/storage/media_content/'.$parent.'/' ;
	   $target_fname=$target_dir.safe_file_names($tiket_id.'_'.basename($fname)) ;
	   if (!file_exists($target_dir)) create_dir($target_dir) ;
	   if (file_exists($target_fname)) unlink($target_fname) ;
	   copy($source_fname,$target_fname) ;

	   $rec['clss']=475 ;
       //$rec['account_id']=MEMBER()->id ;
       $rec['parent']=$tiket_id ;
       $rec['question_id']=$tiket_id ;
       $rec['obj_name']=$fname ;
       $rec['file_name']=basename($target_fname) ;
       $rec['dir']=hide_server_dir($target_dir) ;
        list($size_info,$file_type)=$this->get_small_file_info(_TEMP_DIR.$fname) ;
       $rec['type']=$file_type ;
       $rec['size']=$size_info ;
       //$rec['comment']=$data['comment'] ;
       $id=adding_rec_to_table('media_content_content',$rec) ;
       return($id) ;
	 }

	function tiket_create($media_content_id,$rec_question,$recs_answers)
    {
        $tiket_id=$this->question_create($media_content_id,$rec_question) ;
        if (_sizeof($recs_answers)) foreach($recs_answers as $rec_answer) if ($rec_answer['obj_name']) $this->answers_create($tiket_id,$rec_answer) ;

	}

	function tiket_save($tiket_id,$rec_question,$recs_answers)
    {   update_rec_in_table('media_content_questions',$rec_question,'pkey='.$tiket_id) ;
        if (_sizeof($recs_answers)) foreach($recs_answers as $answer_id=>$rec_answer)
        { if ($answer_id) update_rec_in_table('media_content_answers',$rec_answer,'pkey='.$answer_id) ;}
    }

	function update_stats()
	 {
	     $stats=execSQL_van('select count(*) as cnt,min(c_data) as date_from,max(c_data) as date_to from media_content_result') ;
		 echo 'Первый день контроля знаний: '.date('d.m.Y',$stats['date_from']).'<br>' ;
		 echo 'Последний день контроля знаний: '.date('d.m.Y',$stats['date_to']).'<br>' ;
		 echo 'Число записей по контролю знаний: '.$stats['cnt'].'<br>' ;

	//     execSQL_update('delete from media_content_stats') ;
		 $last_day_of_stats=execSQL_value('select max(day) from media_content_stats') ;
		 if ($last_day_of_stats)
		 {  echo 'Последний день собранной статистики: '.date('d.m.Y',$last_day_of_stats).'<br>' ;
		 	$t=getdate($last_day_of_stats) ;
		    $last_day_of_stats=mktime(0,0,0,$t['mon'],$t['mday']+1,$t['year']);  // в статистике дата ставиться началом дня
		 }

		 $data_from=($last_day_of_stats)? $last_day_of_stats:$stats['date_from'] ;


	     $t=getdate($data_from) ;
		 $from=mktime(0,0,0,$t['mon'],$t['mday'],$t['year']);
		 $t=getdate($stats['date_to']) ;
		 $to=mktime(0,0,0,$t['mon'],$t['mday'],$t['year'])-1;
		 echo 'Будет собрана статистика с : <strong>'.date('d.m.Y',$data_from).'</strong> по <strong>'.date('d.m.Y',$to).'</strong><br>' ;
		 $t=$from ;  $i=0 ;
		 $cnt=execSQL_value('select count(*) as cnt from media_content_result where c_data>='.$data_from.' and c_data<'.$to) ;
		 if ($cnt)


		 while($t<=$to)
		 {  $t2=$t+60*60*24 ;
		 	echo 'Обрабатываем день <strong>'.date('d.m.Y',$t).'</strong><br>' ;
		 	$cnt=execSQL_value('select count(*) from media_content_result where c_data>='.$t.' and c_data<'.$t2) ;
		 	//echo 'Будет обработано <strong>'.$cnt.'</strong> записей по контролю знаний<br>' ;

		 	$stats=execSQL('select t2.parent as dep_id,t2.working,t1.question_id,t1.correct,count(t1.pkey) as cnt_questions
								from media_content_result t1
								left join obj_site_personals t2 on t2.pkey=t1.personal_id 
								where t1.c_data>='.$t.' and t1.c_data<'.$t2.'
								group by t2.parent,t2.working,t1.question_id,t1.correct
								order by t2.parent,t2.working,t1.question_id,t1.correct
								',0,1) ;
			//echo 'Получено <strong>'.$cnt.'</strong> записей статистки<br>' ;
			 $result=array() ;
		 	if (_sizeof($stats)) foreach($stats as $stat)
		    { $result[$stat['dep_id']][$stat['working']][$stat['question_id']]['all']+=$stat['cnt_questions'] ;
		      if ($stat['correct']) $result[$stat['dep_id']][$stat['working']][$stat['question_id']]['correct']+=$stat['cnt_questions'] ;
		    }

		 	//damp_array($result,1,-1) ;

		 	$cur_time=getdate($t) ;
		 	$year=mktime(0,0,0,1,1,$cur_time['year']);
		 	$month=mktime(0,0,0,$cur_time['mon'],1,$cur_time['year']);
		 	$day=mktime(0,0,0,$cur_time['mon'],$cur_time['mday'],$cur_time['year']);

		 	foreach($result as $dep_id=>$arr_workers)
		 	  foreach($arr_workers as $work_id=>$arr_questions)
		 	    foreach($arr_questions as $question_id=>$arr_result)
		          multiSQL_insert('media_content_stats')->append(array( 'clss'=>477,
					                                           'indx'=>1,
					                                           'year'=>$year,
					                                           'month'=>$month,
					                                           'day'=>$day,
					                                           'dep_id'=>$dep_id,
					                                           'work_id'=>$work_id,
					                                           'question_id'=>$question_id,
					                                           'cnt_all'=>($arr_result['all'])? $arr_result['all']:0,
					                                           'cnt_correct'=>($arr_result['correct'])? $arr_result['correct']:0
				                                         )) ;



		 	$t=$t2 ;  $i++ ;
			//if ($i>4) break ;
		 }
		 else echo 'В данном периоде нет результатов ответов<br>' ;

		 multiSQL_insert('media_content_stats')->flush() ;
	 }


	function theme_export($theme_id)
	{  $rec_theme=media_content()->get_theme_by_id($theme_id) ;
	   if (!$rec_theme['pkey']) return(array('error'=>'Тема не найдена'));
	   $recs_sections=execSQL('select * from media_content_themes where parent='.$rec_theme['pkey']) ;
	   $recs_questions=execSQL('select * from media_content_questions where parent in (select pkey from media_content_themes where parent='.$rec_theme['pkey'].')') ;
	   $recs_answers=execSQL('select * from media_content_answers where parent in (select pkey from media_content_questions where parent in (select pkey from media_content_themes where parent='.$rec_theme['pkey'].'))') ;
	   $recs_content=execSQL('select * from media_content_content where parent in (select pkey from media_content_questions where parent in (select pkey from media_content_themes where parent='.$rec_theme['pkey'].'))') ;
	   $result['thema']=array('id'=>$rec_theme['pkey'],'name'=>$rec_theme['obj_name'])  ;
	   if (_sizeof($recs_sections)) foreach($recs_sections as $id=>$rec) $result['sections'][$id]=array('name'=>$rec['obj_name'],'parent'=>$rec['parent']) ;
	   if (_sizeof($recs_questions)) foreach($recs_questions as $id=>$rec) $result['tikets'][$id]=array('text'=>$rec['obj_name'],'section_id'=>$rec['parent'],'timeout'=>$rec['timeout']) ;
	   if (_sizeof($recs_answers)) foreach($recs_answers as $id=>$rec) $result['answers'][$id]=array('indx'=>$rec['indx'],'text'=>$rec['obj_name'],'tiket_id'=>$rec['parent'],'status'=>$rec['status']) ;
	   if (_sizeof($recs_content)) foreach($recs_content as $rec)
	     {   $rec_content=array('name'=>$rec['obj_name'],'tiket_id'=>$rec['parent']) ;
	         if (file_exists(_DIR_TO_ROOT.$rec['dir'].$rec['file_name'])) $rec_content['data']=base64_encode(file_get_contents(_DIR_TO_ROOT.$rec['dir'].$rec['file_name'])) ;
	         $result['contents'][]=$rec_content ;
	     }
	   $json_content=json_encode($result) ;
	   $fname='media_content_theme_'.safe_file_names($rec_theme['obj_name']).'.json' ;
	   $fdir=_TEMP_DIR.'/'.$fname ;
	   file_put_contents($fdir,$json_content) ;

	   $result=array() ;
	   $result['Разделов']=_sizeof($recs_sections) ;
	   $result['Билетов']=_sizeof($recs_questions) ;
	   $result['Ответов']=_sizeof($recs_answers) ;
	   $result['Файлов']=_sizeof($recs_content) ;
	   $result['Файл экпорта']=$fname ;
	   $result['Размер файла']=show_size(strlen($json_content)) ;
	   return($result) ;

	}

}



?>
