<?php
class report_generate_quiz_results extends c_report
{
 var $title='Генерация результатов контроля знаний' ;
 var $view_by_space_filter=1 ;
 var $event_id=0 ;
 var $personal_id=0 ;
 var $rec_lession=array() ;
 var $rec_event=array() ;
 var $event_ext=array() ;
 var $allow_export_to_csv=1 ;


 function setting($options=array())
 {    if ($this->personal_id)   $usl_select_results='t1.personal_id='.$this->personal_id ;
      else if ($this->event_id) $usl_select_results='t1.event_id='.$this->event_id ;
      else                      $usl_select_results=1 ;
      $arr_events=execSQL('select distinct(t1.event_id) as event_id,t2.pkey as event_pkey,t2.obj_name
                           from quiz_result t1
                           left join obj_site_events_schedule t2 on t2.pkey=t1.event_id
                           where not t2.pkey is null and '.$usl_select_results) ;

      $_usl=array() ;
     $_usl[]='not t3.parent is null' ;
     if ($this->personal_id)    $_usl[]='t1.personal_id='.$this->personal_id ;
     if ($this->event_id)       $_usl[]='t1.event_id='.$this->event_id ;
     $usl_theme_select=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

     $parent_themes = execSQL('select t3.pkey,t3.parent,t3.parent2,t3.level,t3.obj_name 
                          from quiz_result t1 
                                        inner join quiz_questions t2 on t2.pkey=t1.question_id 
                                        inner join quiz_themes t3 on t3.pkey=t2.parent
                          where '.$usl_theme_select.'   
                                        group by t3.pkey
                                        order by t3.pkey
        ');

     $themes=execSQL('select pkey,clss,obj_name,parent,level,parent2 from quiz_themes where level>0 order by level,parent');

     $themes=$this->hierarchy_array($themes);


     $max_level=0;
     foreach ($themes as $key=>&$theme) {
         if ($theme['level']>$max_level) $max_level=$theme['level'];
         if (_sizeof($parent_themes[$key])) { $theme['in_view']=true;}
     }

     if ($max_level>0) {
         for ($i=$max_level;$i>0;$i--) {
             foreach ($themes as $key=>$theme) {
                 if ($theme['level']!=$i) continue;
//                 if (!$theme['in_view']) {
//                     unset($themes[$key]);
//                     continue;
//                 }
//                 if ($theme['parent']) {
//                     $themes[$theme['parent']]['in_view']=true;
//                 }
                 if ($theme['clss']==481) unset($themes[$key]);
             }
         }
     }

       $arr_themes=array() ; $arr_themes_section=array() ;

     foreach ($themes as $key=>$theme) {
         if ($theme['level']==2) {
             $arr_themes[$key]=$theme['obj_name'] ;
//                $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;
         } elseif ($theme['level']>2) {
             $arr_themes_section[$theme['parent2']][$key]=$this->empty_space($theme['level']).$theme['obj_name'] ;
         }
      }
      //$arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
      //echo _CUR_REPORT_DIR ;

    $this->form_open() ;

    if (!$this->personal_id)
    { $this->row_open() ;

      $options_select=['viewer_name'=>$this->rec_event['viewer_name']] ;
      $arr_orgs_ids=PERSONAL()->get_arr_orgs_to_cur_account('',$options_select) ;
      $arr_otdel_ids=(_sizeof($this->filter['dep_ids']))? PERSONAL()->get_arr_otdels_to_cur_account($this->filter['dep_ids'],'',$options_select):array() ;
      $arr_workd_ids=PERSONAL()->get_arr_works_to_cur_account('',$this->filter['dep_ids'],$this->filter['otdel_ids'],$options_select) ;

      $this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
      //$this->filter_section_select_multiple('dep_ids','Организация:',4,$arr_orgs_ids) ;
      //$this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids) ;
      //$this->filter_section_select_multiple('working_ids','Должность:',4,$arr_workd_ids) ;
      $this->row_close() ;
    }

    $this->row_open() ;
    //if (!$this->event_id) $this->filter_section_select('event_id','Мероприятие:',2,$arr_events) ;
    $this->filter_section_select('theme_id','Тема КЗ:',2,$arr_themes) ;
//    if ($this->filter['theme_id']) $this->filter_section_select_multiple('section_ids','Разделы КЗ:',4,$arr_themes_section[$this->filter['theme_id']]) ;
     if ($this->filter['theme_id']) $this->filter_section_select('section_id','Раздел КЗ:',3,$arr_themes_section[$this->filter['theme_id']]) ;
    $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
    $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;

    $this->row_close() ;
    $this->panel_buttons() ;
    $this->form_close() ;

  }


  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;
     $usl=array() ;
     $usl[]=1 ;
     if ($this->event_id) $usl[]='t1.event_id='.$this->event_id ;
     if ($this->personal_id) $usl[]='t1.personal_id='.$this->personal_id ;


     if ($this->filter['personal_id'])        $usl[]='t2.pkey='.$this->filter['personal_id'] ;
     if ($this->filter['name'])            $usl[]='t2.obj_name like "%'.$this->filter['name'].'%"' ;
     if ($this->filter['dep_ids'])         $usl[]='t2.parent2 in ('.implode(',',array_keys($this->filter['dep_ids'])).')' ;
     if ($this->filter['otdel_ids'])       $usl[]='t2.parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
     if (_sizeof($this->filter['working_ids'])) $usl[]='working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;
     if ($this->filter['data_from'])        $usl[]='t1.c_data>='.strtotime($this->filter['data_from']) ;
     if ($this->filter['data_to'])          $usl[]='t1.c_data<='.strtotime($this->filter['data_to']) ;
     if ($this->session_ids)          $usl[]='t1.quiz_id in ('.$this->session_ids.')' ;
     if ($this->question_ids)          $usl[]='t1.question_id in ('.$this->question_ids.')' ;

//      if ($this->filter['theme_id'])
//      {   $questions_ids=[] ;
//          if (!_sizeof($this->filter['section_ids'])) $section_ids=execSQL_line('select pkey as id from quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
//          else                                       $section_ids=array_keys($this->filter['section_ids']) ;
//          if (_sizeof($section_ids)) $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent in ('.implode(',',$section_ids).')') ;
//          if (_sizeof($questions_ids)) $usl[]='question_id in ('.implode(',',$questions_ids).')';
//      }

      if ($this->filter['theme_id'])
      {   $questions_ids=[] ; $section_ids=[];
          if (!$this->filter['section_id']) $section_ids=execSQL_line('select pkey as id from quiz_themes where parent2='.$this->filter['theme_id'].' ') ;
          else {
              $section_level=execSQL_value('select level from quiz_themes where pkey='.$this->filter['section_id']);
              if ($section_level) {
                  $section_ids=execSQL_line('select pkey as id from quiz_themes where parent'.$section_level.'='.$this->filter['section_id'].' ') ;
                  if (!_sizeof($section_ids)) $section_ids=[$this->filter['section_id']];
              }
          }
          if (_sizeof($section_ids))  {
              $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent in ('.implode(',',$section_ids).')') ;
          } else {
              $questions_ids=execSQL_line('select pkey as id from quiz_questions where parent='.$this->filter['theme_id']) ;
          }
          if (_sizeof($questions_ids)) $usl[]='question_id in ('.implode(',',$questions_ids).')';
          else $usl[]='question_id=-1';
      }

//      if ($this->filter['data_from'])          $_usl[]='c_data>='.strtotime($this->filter['data_from']) ;
//      if ($this->filter['data_to'])            $_usl[]='c_data<='.strtotime($this->filter['data_to']) ;




     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl,1,-1) ;
     //damp_array($_usl_select_events,1,-1) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $title='' ;
   $info=$this->get_arr_info_filters() ;
   if ($this->filter['theme_id'])                        $info['Тема КЗ']=QUIZ()->get_theme_name_by_id($this->filter['theme_id']);
   if ($this->filter['section_id'])                      $info['Раздел КЗ']=QUIZ()->get_theme_name_by_id($this->filter['section_id']);

   if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<div class=center>'.implode(' ',$_str).'</div>' ;
   return $title ;
   }



  function get_cnt_items($usl,$options=array())
  {
    //$options['debug']=2 ;
    $cnt=execSQL_value('select count(t1.pkey)
                        from  quiz_result t1
                        left join view_personals t2 on t2.pkey=t1.personal_id 
                        left join quiz_questions t3 on t3.pkey=t1.question_id 
                        left join quiz_themes t5 on t5.pkey=t1.theme_id 
                        where '.$usl.'
                        ',$options) ;
    return($cnt) ;

  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    //$options['debug']=1 ;
    $options['no_indx']=1 ;
    $order=($options['order'])? ' order by '.$options['order']:' order by t1.pkey desc' ;

 	$list_recs=execSQL('select t1.pkey as quiz_pkey,t1.c_data as quiz_data,t5.pkey as theme_id,t1.question_id,t1.correct,t1.quiz_id,t1.mo_id,t1.event_id,
                        t2.*,
                        t3.obj_name as question_text,
                        t5.obj_name as theme_name,
                        t4.pkey as rasdel_id,t4.obj_name as rasdel_name,t4.clss as rasdel_clss,t4.parent as rasdel_parent,
                        t7.obj_name as event_name 
                        from  quiz_result t1    
                        left join view_personals t2 on t2.pkey=t1.personal_id 
                        left join quiz_questions t3 on t3.pkey=t1.question_id 
                        left join quiz_themes t4 on t4.pkey=t3.parent 
                        left join quiz_themes t5 on t5.pkey=t4.parent2 
                        left join obj_site_events_schedule t7 on t7.pkey=t1.event_id 
                        where '.$usl.$order.$limit,$options) ;
    //print_2x_arr($list_recs) ;
    return($list_recs) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {// print_2x_arr($list_recs) ;
    $id=($options['id'])? 'id='.$options['id']:'' ;
    $i=1 ;
    include(_DIR_EXT.'/personal/panel_personal_info.php') ;

    $section_names=[];

    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>ID</th>
            <th>ID сессии КЗ</th>
            <th>ID сессии МО</th>
            <th>Дата/время</th>
            <?if (!$this->event_id){?><th>Мероприятие</th><?}?>
            <th>Тема</th>
            <th>Раздел</th>
            <th>Вопрос</th>
            <th>Правильный ответ</th>
            <?if (!$this->personal_id)
              {?><th>Сотрудник</th>
                 <th>Место работы</th>
                 <th>Должность</th>
               <?
              }?>
         </tr><?
         if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {  $rec['__href_mo']='/cab/mo/'.$rec['mo_id'].'/' ;
             $rec['__href']='/cab/quiz/kz/'.$rec['quiz_id'].'/' ;// ? quiz_pkey
             $rec['__href_window']='/window/personal/person/'.$rec['pkey'].'/' ; // ? quiz_pkey

             if ($rec['rasdel_clss']==481) { //если родительский раздел - знание
                 if ($section_names[$rec['rasdel_parent']]) {
                     $rec['rasdel_name']=$section_names[$rec['rasdel_parent']];
                 } else {
                     $section_names[$rec['rasdel_parent']]=execSQL_value('select obj_name from quiz_themes where pkey='.$rec['rasdel_parent']);
                     $rec['rasdel_name']=$section_names[$rec['rasdel_parent']];
                 }
             }

             if (!$rec['theme_name'] and $rec['rasdel_name']) {
                 $rec['theme_name']=$rec['rasdel_name'];
                 $rec['rasdel_name']='';
             }

              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['quiz_id']?></a></td>
                  <td><?if ($rec['mo_id']){?><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href_mo']?>"><?echo $rec['mo_id']?></a><?}?></td>
                  <td class="nowrap"><?echo date('d.m.Y H:i',$rec['quiz_data'])?></td>
                  <?if (!$this->event_id){?><td><?echo $rec['event_name']?></td><?}?>
                  <td class="left"><? echo $rec['theme_name']?></td>
                  <td class="left"><? echo $rec['rasdel_name']?></td>
                  <td class="left"><? echo $rec['question_text']?></td>
                  <td class="center"><?echo ($rec['correct'])? '<span class=green>Да</span>':'<span class=red>Нет</span>'?></td>
                  <?if (!$this->personal_id)
                  { ?><td class="left"><?panel_personal_info_small($rec)?></td>
                      <td class="left"><?echo '<strong>'.$rec['_org_name'].'</strong><br><div class="small">'.$rec['_otdel_name'].'</div>'?></td>
                      <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']  ;
                                        if ($rec['working2']) echo '<br><strong>Совмещение: </strong>'._IL('IL_works')->recs[$rec['working2']]['obj_name'] ; ?>
                      </td>
                  <?}
                  ?>
              </tr><?
              $i++;
          }
      ?></table><?
  }

    function print_template_CSV($list_recs,$options=array())
          { $i=$options['from'] ;
            if (_sizeof($list_recs)) foreach($list_recs as $rec)
            {   $data=array() ;
        	    $data['№']=$i+1 ;
                $data['ID сессии КЗ']=$rec['quiz_pkey']  ;
                $data['ID сессии МО']=$rec['mo_id'] ;
                $data['Дата/время']=date('d.m.Y H:i',$rec['quiz_data'])  ;
                $data['ID темы']=$rec['theme_id']  ;
                $data['Тема']=$rec['theme_name']  ;
                $data['ID раздела']=$rec['rasdel_id']  ;
                $data['Раздел']=$rec['rasdel_name']  ;
                $data['ID вопроса']=$rec['question_id']  ;
                $data['Вопрос']=$rec['question_text']  ;
                $data['Правильный ответ']=($rec['correct'])? 'Да':'Нет'  ;
                $data['GUID сотрудника']=$rec['uid']  ;
        	    $data['ФИО сотрудника']=$rec['obj_name']  ;
                $data['Дата рождения']=$rec['dr']  ;
                $data['Возраст']=$rec['age']  ;
                $data['Пол']=($rec['pol'])? 'Женский':'Мужской'  ;
        	    $data['Организация']=$rec['_org_name'] ;
        	    $data['Подразделение']=$rec['_otdel_name'] ;
        	    $data['Должность']= _IL('IL_works')->recs[$rec['working']]['obj_name'] ;
                // вносим данные в csv
                $this->put_data_to_CSV($data,$i) ;
        	    $i++ ;
    	}

         }

    function hierarchy_array($arr,$prev_parent=0) {
        $temp_arr=[];
        foreach ($arr as $key=>$value) {
            if ($value['parent']==$prev_parent) {
                $temp_arr[$key]=$value;
                $temp_arr2=$this->hierarchy_array($arr,$value['pkey']);
                if (_sizeof($temp_arr2)) $this->merge_arr($temp_arr,$temp_arr2);
            }
        }
        return $temp_arr;
    }

    function merge_arr(&$arr1,$arr2)
    {
        if (_sizeof($arr1)) {
            foreach ($arr2 as $key=>$value) {
                $arr1[$key]=$value;
            }
        } else {
            $arr1=$arr2;
        }

    }

    function empty_space($level) {
        $min=4;
        $result='';
        if ($level>=$min) {
            for ($i=$min;$i<=$level;$i++) {
                $result.='&nbsp;&nbsp;&nbsp;';
            }
        }
        return $result;
    }


}

?>
