<?php
include_once(_DIR_EXT."/events_quiz/i_event_quiz.php");
include_once(_DIR_TO_CLASS."/c_page.php");
class c_page_cab_events_quiz_card extends c_page
{
  public $h1='Карточка мероприятия по проверке знаний' ;
  var $rec_event ;
  var $rec_lession ;
  var $obj_event ;
  var $rec_theme ;
  var $arr_link_themes ;

 function select_obj_info()
 { if (_CUR_ID)
   { $this->rec_event=EVENTS()->get_event_by_id(_CUR_ID) ;
     if ($this->rec_event['pkey'])
     { $this->obj_event=EVENTS()->get_event_obj_by_ext($this->rec_event['ext']) ;
       $this->obj_event->rec_event=$this->rec_event ;
       $this->h1=$this->rec_event['obj_name'] ;
       $this->arr_link_themes=execSQL('select * from quiz_themes where event_id='.$this->rec_event['pkey']) ;
     }
     if (!$this->rec_event['pkey']) $this->result=404 ;
   } else $this->result=404 ;

 }

 function menu_config()
 { if ($this->no_event_menu) { parent::menu_config() ; return ; }

   // полчаем список участников мероприятия с учетом динамической подгрузки списка участников
   //$arr_cnt=EVENTS()->get_event_personals_status($this->rec_event['pkey'],array('only_active'=>1)) ;
   $arr_cnt=EVENTS()->get_event_personals_status($this->rec_event['pkey']) ;
   $all=array_sum($arr_cnt) ;
   if ($this->rec_event['pkey'])
    { $this->menu[$this->rec_event['__href']]='Карточка КЗ' ;
      $this->menu[$this->rec_event['__href'].'edit/step1/']='Редактировать' ;
      //$this->menu[$this->rec_event['__href'].'personals/']='Все участники' ;
      $this->menu[$this->rec_event['__href'].'personals/']=array('title'=>'Все участники','info_value'=>(($all)? '<span>'.$all.'</span>':'')) ;
      $this->menu[$this->rec_event['__href'].'personals/none/']=array('title'=>'Подлежат','info_value'=>(($arr_cnt[1])? '<span>'.$arr_cnt[1].'</span>':'')) ;
      $this->menu[$this->rec_event['__href'].'personals/part/']=array('title'=>'Частично прошли','info_value'=>(($arr_cnt[2])? '<span>'.$arr_cnt[2].'</span>':'')) ;
      $this->menu[$this->rec_event['__href'].'personals/full/']=array('title'=>'Прошли проверку','info_value'=>(($arr_cnt[3])? '<span>'.$arr_cnt[3].'</span>':'')) ;
      $this->menu[$this->rec_event['__href'].'reports/']=array('title'=>'Отчеты') ;
      //$this->menu[$this->rec_event['__href'].'log/']='История' ;
      $this->menu[$this->rec_event['__href'].'db/']='Исходные данные' ;
      $this->page_type='window' ;
    }

 }

    function second_menu_config()
   { $this->second_menu[$this->rec_event['__href']]=array('title'=>'Карточка мероприятия') ;
     //$this->second_menu[$this->rec_event['__href'].'edit/step1/']=array('title'=>'Редактировать') ;
     //$this->second_menu[$this->rec_event['__href'].'log/']='История' ;
     //$this->second_menu[$this->rec_event['__href'].'db/']='Исходные данные' ;
     //$this->second_menu[$this->rec_event['__href'].'check/']='Проверки' ;
   }

 function block_main()
 {
   $this->page_title() ;
   $this->panel_event_info() ;

   // проверяем, связано ли мероприятие с темами КЗ. Если связано - не показывать панель выбора тем КЗ
   if (!_sizeof($this->arr_link_themes)) $this->panel_events_themes(); // показ собственных тем КЗ
   else                                 $this->panel_themes_stats();  // показ тем КЗ, которые слинкованы с мероприятием

   //$this->panel_stats_by_org() ;
 }

    function panel_event_info()
        {   // данные по участникам мероприятия с учетом группы текущего аккаунта
           //$arr_personals_status=EVENTS()->get_event_personals_status($this->rec_event['pkey']) ;
           //$personals_count=array_sum($arr_personals_status) ;
           //damp_array($this->rec_event) ;

           ?><table class="basic auto fz_small setting events">
                <tr><th>Наименование:</th><td><?echo $this->rec_event['obj_name']?></td></tr>
                <tr><th>Статус:</th><td><?echo $this->rec_event['_status']?></td></tr>
                <tr><th>Срок проведения, от:</th><td><?echo ($this->rec_event['date_from'])? date('d.m.Y H:i',$this->rec_event['date_from']):'-'?></td></tr>
                <tr><th>Срок проведения, до:</th><td><?echo ($this->rec_event['date_to'])? date('d.m.Y H:i',$this->rec_event['date_to']):'-'?></td></tr>
                <tr><th>Переодичность прохождения:</th><td><?echo QUIZ()->arr_events_close_period[$this->rec_event['_ext_info']['close_period']]?></td></tr>
                <tr><th>Условия прохождения:</th><td><?echo QUIZ()->arr_events_close_status[$this->rec_event['_ext_info']['close_status']]?></td></tr>
                <tr><th>Условие отбора участников:</th><td><?echo $this->rec_event['_ext_info']['info_filter']?></td></tr>
                <tr><th>Место проведения:</th><td><?echo implode('<br>',$this->rec_event['_ext_info']['_group_ids'])?></td></tr>
                <tr><th>Дни показа контента:</th><td><?echo ($this->rec_event['_ext_info']['allow_days'])? $this->obj_event->arr_allow_days[$this->rec_event['_ext_info']['allow_days']]:'Все'?></td></tr>
            </table>
            <style type="text/css">
            </style>
           <?
 }

 function panel_stats_by_org()
 {
   $themes_ids=implode(',',$this->rec_event['_ext_info']['themes_ids']) ;
   $tiket_ids=array() ;
   //echo '$themes_ids='.print_r($themes_ids,true).'<br>' ;
   if ($themes_ids)
 	{ $str_ids=$themes_ids;
 	  // получаем все разделы которые внутри указанной темы/раздела или сам раздел
 	  $recs_rasdels=execSQL_line('select pkey from quiz_themes where pkey in ('.$str_ids.') or parent1 in ('.$str_ids.') or parent2 in ('.$str_ids.')  or parent3 in ('.$str_ids.')  or parent4 in ('.$str_ids.')  or parent5 in ('.$str_ids.')  or parent6 in ('.$str_ids.')  or parent7 in ('.$str_ids.')  or parent8 in ('.$str_ids.') or parent9 in ('.$str_ids.')',0,1) ;
 	  if (_sizeof($recs_rasdels)) $tiket_ids=execSQL_line('select pkey,obj_name from quiz_questions where parent in ('.implode(',',$recs_rasdels).')',0) ;

 	  //$use_rasdel=$recs_rasdels[array_rand($recs_rasdels)] ;
 	  //echo '$use_rasdels='.$use_rasdel.'<br>' ;
    }

     //t1.question_id in ('.implode(',',$tiket_ids).')

   $stats=execSQL('select t2._org_id,t3.obj_name,t1.correct,count(t1.pkey) as cnt_questions 
            from  quiz_result t1
            left join  view_personals t2 on t2.pkey=t1.personal_id
            left join  obj_site_personals t3 on t3.pkey=t2._org_id
            left join quiz_questions t4 on t4.pkey=t1.question_id 
            left join obj_site_events_pass t5 on t5.pkey=t1.quiz_id
            where not t2._org_id is null
                  and t2.enabled=1 
                  and t5.event_id='.$this->rec_event['pkey'].'
                  and not t4.pkey is null
            group by t2._org_id,t1.correct
           ',0,1) ;

     $stats2=array() ;
   if (_sizeof($stats))  foreach($stats as $rec)
   { $stats2[$rec['_org_id']]['all']+=$rec['cnt_questions'] ;
     if ($rec['correct'])  $stats2[$rec['_org_id']]['correct']=$rec['cnt_questions'] ;
     $stats2[$rec['_org_id']]['org_name']=$rec['obj_name'] ;
   }
   ?><table class="basic fz_small full"><tr><th>Организация</th><th>Задано вопросов</th><th>Правильных ответов</th><th>Процент правильных ответов</th></tr><?
   if (_sizeof($stats2)) foreach($stats2 as $rec)
   { ?><tr>
         <td><?echo $rec['org_name']?></td>
         <td><?echo $rec['all']?></td>
         <td><?echo $rec['correct']?></td>
         <td><?echo round($rec['correct']/$rec['all']*100)?>%</td>

      </tr><?

   }
   ?></table><?

   //damp_array($stats2) ;


   /*  $recs=execSQL('select t1._org_id,t1._org_name,t1._otdel_id,t1._otdel_name,t1.event_status,count(t1.pkey) as cnt
                           from view_event_personals t1
                           group by t1._org_id,t1._otdel_id,t1.event_status
                           order by t1._org_name,t1._otdel_name
                            ',1,1) ;

   ?><h2>Статистика проверки знаний по организациям:</h2><?
   include_once(_DIR_EXT.'/events_quiz/report_quiz_info_by_orgs.php') ;
   $report_obj=new report_quiz_info_by_orgs() ;
   $report_obj->event_id=$this->rec_event['pkey'] ;
   $report_obj->filter['group_id']=MEMBER()->cur_group_id ;
   $report_obj->setting() ;
   //$report_obj->view() ;   */
 }


  function panel_events_themes()
  {   //damp_array($this->obj_event) ;
      $themes_ids=$this->rec_event['_ext_info']['themes_ids'] ;
      //damp_array($themes_ids);

      ?><div id="panel_events_themes"><h2>Темы проверки знаний</h2><?
      if (_sizeof($themes_ids)) $recs_themes=execSQL('select * from quiz_themes where pkey in ('.implode(',',array_keys($themes_ids)).') order by indx') ;

       ?><table class="basic fz_small full auto"><tr class="head"><th>ID</th><th>Наименование</th></tr><?
           if (_sizeof($recs_themes)) foreach($recs_themes as $rec)
           {   $arr=TREE('quiz_themes')->get_arr_parents_names($rec['pkey']) ;

               ?><tr>
                 <td style="width:100px;" class="indx center"><?echo $rec['pkey']?></td>
                 <td style="width:auto;" class="left"><div style="font-size:18px;"><?echo implode(' / ',$arr)?></div><br>
                     <?
                    /* $recs=execSQL_row('select t1.working_id,t2.obj_name
                                         from quiz_workings2 t1
                                         left join view_IL_works t2 on t2.pkey=t1.working_id
                                         where t1.theme_id='.$rec['pkey']) ;
                     if (_sizeof($recs))  echo '<strong>Должности, сотрудники которых подлежат контролю знаний по данной теме:</strong><br>'.implode(', ',$recs).'<br><br>' ;

                     $recs=execSQL_line('select section_id from quiz_orgs where section_id>0 and theme_id='.$rec['pkey']) ;
                     if (_sizeof($recs))
                     { ?><strong>Организации/подразделения, сотрудники которых подлежат контролю знаний по данной теме:</strong><br><?
                       foreach($recs as $id)
                         {
                             $arr=TREE('obj_site_personals')->get_arr_parents_names($id,array('from_level'=>2));
                             //print_r($arr) ;
                             echo implode(' / ',$arr).'<br>' ;

                         }
                     }*/
                     ?>


                 </td>
               </tr>
             <?
           }
           ?>
            </table>
            <style type="text/css">
               table.basic td.indx{text-align:center;}
               table.basic td.indx:hover i{display:inline;cursor:pointer;}
               table.basic ul{margin:0 0 0 20px;;padding:0;}
               table.basic ul li{padding:0;margin:0;}
            </style>
            </div>
           <?
  }

    function panel_themes_stats()
     { ?><h3>Темы и разделы КЗ, которые будут доведены в данном мероприятии</h3><?
       $recs_themes=execSQL('select * from quiz_themes where parent=1 and event_id='.$this->rec_event['pkey'].' order by obj_name') ;

       $arr_events=execSQL('select t1.pkey,t1.event_id,t2.obj_name as event_name from quiz_themes t1 left join obj_site_events_schedule t2 on t2.pkey=t1.event_id where t1.event_id>0 and t2.enabled=1 and t2.status<5') ;
/*
       $recs_workings=execSQL('select t1.theme_id,t1.working_id,t2.obj_name
                               from quiz_workings2 t1
                               left join view_IL_works t2 on t2.pkey=t1.working_id
                               ',0,1) ;
       $recs_themes_workings=[] ;
       if (_sizeof($recs_workings)) foreach($recs_workings as $rec) $recs_themes_workings[$rec['theme_id']][]=$rec['obj_name'] ;

       $recs_themes_orgs=[] ;
       $arr_orgs=execSQL('select theme_id,org_id from quiz_orgs where org_id>0',0,1) ;
       if (_sizeof($arr_orgs)) foreach($arr_orgs as $rec)
        {
            $arr=TREE('obj_site_personals')->get_arr_parents_names($rec['org_id'],array('from_level'=>2));
            $recs_themes_orgs[$rec['theme_id']][]=implode(' / ',$arr) ;
        }
*/


       ?><table class="basic fz_small full auto">
            <tr><th>ID</th>
                <th>Тема/раздел</th>
                <th>Число билетов</th>
                <th>Условие отбора сотрудников</th>
                <th>Число сотрудников</th>
            </tr>
         <? if (_sizeof($recs_themes)) foreach($recs_themes as $rec_theme)
             {  $recs_sections=execSQL('select * from quiz_themes where parent='.$rec_theme['pkey'].' and filter!="" order by obj_name') ;
                if (_sizeof($recs_sections)) foreach($recs_sections as $rec_section)
                {   $child_ids=$childs_sections=TREE('quiz_themes')->get_list_child($rec_section['pkey']) ;
                    $child_ids[$rec_section['pkey']]=1 ;
                    $cnt_tikets=execSQL_value('select count(pkey) as cnt from quiz_questions where parent in ('.implode(',',array_keys($child_ids)).')') ;

                    $arr=TREE('quiz_themes')->get_arr_parents_names($rec_section['pkey']) ;
                    $count=execSQL_value('select count(pkey) from '.$rec_section['viewer_name']) ;
                    ?><tr>
                         <td><?echo $rec_section['pkey']?></td>
                         <td class="left"><?echo implode(' / ',$arr)?></td>
                         <td><?echo $cnt_tikets?></td>
                         <td><div style="width:600px;height:100px;overflow:scroll;"<?echo nl2br($rec_section['info_filter'])?></div></td>
                         <td><?echo $count?></td>
                     </tr><?

                }


             }


         ?>

        </table>
       <?

     }
}



?>
