<?php
include_once('c_post_shift_poll.php');
class c_page_cab_post_shift_poll_info extends c_page_cab_post_shift_poll
{
 public $h1='Опросы - Информация' ;

 function block_main()
 {

     $tables=array(   'post_shift_poll'=>'Основная таблица сессий',
                      'post_shift_poll_result'=>'Результаты ответов',
                   ) ;
     include_once(_DIR_EXT.'/aspmo_debug/c_debug_info.php')  ;
     $page=new c_page_cab_debug_info() ;
     $page->panel_info_db_small($tables) ;



 }

 function CMD_delete_free_tree_item()
 {
    $recs=execSQL('select tree.*,
                   theme.pkey as theme_id, 
                   question.pkey as question_id, 
                   answer.pkey as answer_id 
                   from poll_tree tree
                   left join poll_themes theme on theme.pkey=tree.pkey and tree.i_tkey='._DOT('poll_themes')->pkey.'
                   left join poll_questions question on question.pkey=tree.pkey and tree.i_tkey='._DOT('poll_questions')->pkey.'
                   left join poll_answers answer on answer.pkey=tree.pkey and tree.i_tkey='._DOT('poll_answers')->pkey.'
                   where theme.pkey is null and question.pkey is null and answer.pkey is null
                  ') ;
    if (_sizeof($recs))
    { echo 'Найдено <strong>'._sizeof($recs).'</strong> потерянных элементов дерева<br>' ;
      ?><button class="v1" cmd="delete_free_tree_item_exec">Удалить потерянные элементы дерева</button><?
	}
    else echo '<div class="green">Не найдено потерянных элементов дерева</div>' ;
 }

 function CMD_delete_free_tree_item_exec()
 {
    $recs=execSQL('select tree.*,
                   theme.pkey as theme_id, 
                   question.pkey as question_id, 
                   answer.pkey as answer_id 
                   from poll_tree tree
                   left join poll_themes theme on theme.pkey=tree.pkey and tree.i_tkey='._DOT('poll_themes')->pkey.'
                   left join poll_questions question on question.pkey=tree.pkey and tree.i_tkey='._DOT('poll_questions')->pkey.'
                   left join poll_answers answer on answer.pkey=tree.pkey and tree.i_tkey='._DOT('poll_answers')->pkey.'
                   where theme.pkey is null and question.pkey is null and answer.pkey is null
                  ') ;

    if (_sizeof($recs))
    { execSQL_update('delete from poll_tree where pkey in ('.implode(',',array_keys($recs)).')') ;
      echo 'Удалено <strong>'._sizeof($recs).'</strong> потерянных элементов дерева<br>' ;
	}
 }



 function CMD_truncate_poll_tree()
 {
   execSQL_update('truncate table poll_tree',2) ;
 }

 function CMD_sync_poll_tree()
   {

       $tkey_themes=_DOT('poll_themes')->pkey ;
       $tkey_question=_DOT('poll_questions')->pkey ;
       $tkey_answer=_DOT('poll_answers')->pkey ;

       execSQL_update('update poll_themes set tkey='.$tkey_themes) ;
       execSQL_update('update poll_questions set tkey='.$tkey_question) ;
       execSQL_update('update poll_answers set tkey='.$tkey_answer) ;


                //execSQL('select * from poll_themes',2) ;
                // добавляем только те разделы, родители которых существуют, оторванные разделы игнорируем
                // при добавлении poll_themes в  poll_tree pkey записей должны совпадать
                execSQL('select * from poll_themes',2) ;
                execSQL_update('insert into poll_tree (pkey,clss,enabled,obj_name,temp,i_tkey,i_clss,parent) 
                                select t1.pkey,78,1,t1.obj_name,t1.pkey,t1.tkey,t1.clss,t1.parent 
                                from poll_themes t1
                                left join poll_themes t2 on t2.pkey=t1.parent
                                where not t2.pkey is null or t1.parent=0 
                                ',array('debug'=>2)) ;
                execSQL('select * from poll_tree',2) ;


                // при добавлении вопросов
                // 1. parent берем из уже существующих записей разделов в poll_tree
                // 2. Если записи раздела в poll_tree нет - не добавляем
                execSQL('select * from poll_questions',2) ;
                execSQL_update('insert into poll_tree (clss,enabled,obj_name,temp,i_tkey,i_clss,parent) 
                                select 78,1,t1.obj_name,t1.pkey,t1.tkey,t1.clss,t2.pkey 
                                from poll_questions t1
                                left join poll_tree t2 on t2.temp=t1.parent and t2.i_tkey='.$tkey_themes.'   
                                where not t2.pkey is null  
                                ',array('debug'=>2)) ;
                execSQL('select * from poll_tree',2) ;

                // при добавлении ответов
                // 1. parent берем из уже существующих записей разделов в poll_tree
                // 2. Если записи раздела в poll_tree нет - не добавляем
                execSQL('select * from poll_answers',2) ;
                execSQL_update('insert into poll_tree (clss,enabled,obj_name,temp,i_tkey,i_clss,parent) 
                                select 78,1,t1.obj_name,t1.pkey,t1.tkey,t1.clss,t2.pkey 
                                from poll_answers t1
                                left join poll_tree t2 on t2.temp=t1.question_id and t2.i_tkey='.$tkey_question.'
                                where not t2.pkey is null  
                                ',array('debug'=>2)) ;
                execSQL('select * from poll_tree',2) ;

                TREE('poll_tree')->update_levels_parents();

              $recs=execSQL('select * from poll_tree order by pkey',2) ;
              //return ;

                foreach($recs as $rec)
                {
                  if ($rec['i_tkey']==$tkey_themes)
                  {echo 'Делаем замену для темы: '.$rec['temp'].' => '.$rec['pkey'].'<br>' ;
                    execSQL_update('update poll_themes set pkey='.$rec['pkey'].' where pkey='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_tree set temp='.$rec['pkey'].' where temp='.$rec['temp'].' and i_tkey='.$tkey_themes,array('debug'=>2)) ;
                    execSQL_update('update poll_questions set parent='.$rec['pkey'].' where parent='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_themes_text set parent='.$rec['pkey'].' where parent='.$rec['temp'],array('debug'=>2)) ;
                  }
                  if ($rec['i_tkey']==$tkey_question)
                  { echo 'Делаем замену для вопроса: '.$rec['temp'].' => '.$rec['pkey'].'<br>' ;
                    execSQL_update('update poll_questions set pkey='.$rec['pkey'].' where pkey='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_tree set temp='.$rec['pkey'].' where temp='.$rec['temp'].' and i_tkey='.$tkey_question,array('debug'=>2)) ;
                    execSQL_update('update poll_answers set parent='.$rec['pkey'].' where parent='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_answers set question_id='.$rec['pkey'].' where question_id='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_content set parent='.$rec['pkey'].' where parent='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_content set question_id='.$rec['pkey'].' where question_id='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_result set question_id='.$rec['pkey'].' where question_id='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_stats set question_id='.$rec['pkey'].' where question_id='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_sessions_questions set question_id='.$rec['pkey'].' where question_id='.$rec['temp'],array('debug'=>2)) ;

                  }
                  if ($rec['i_tkey']==$tkey_answer)
                  { echo 'Делаем замену для ответа: '.$rec['temp'].' => '.$rec['pkey'].'<br>' ;
                    execSQL_update('update poll_answers set pkey='.$rec['pkey'].' where pkey='.$rec['temp'],array('debug'=>2)) ;
                    execSQL_update('update poll_tree set temp='.$rec['pkey'].' where temp='.$rec['temp'].' and i_tkey='.$tkey_answer,array('debug'=>2)) ;
                    execSQL_update('update poll_result set answer_id='.$rec['pkey'].' where answer_id='.$rec['temp'],array('debug'=>2)) ;
                  }
                }
	 }

 function panel_poll_crontab()
 {   include_once(_DIR_EXT.'/aspmo_setting/c_ajax.php');
    $c_ajax = new c_page_ajax();

 	 ?> <h2>Задания планировщика</h2>
 	     <form><table class="basic fz_small full auto"><tr><th>Активно</th><th>Статус</th><th>Расписание</th><th>Наименование</th><th>Время последнего запуска</th><th>Длительнось выполнения</th><th>Операция</th></tr>
 	         <?
 	            $list_crontab=execSQL('select pkey,enabled,cmd,obj_name,last_exec,last_exec_end,time_exec,intr,default_intr,status from obj_site_crontab where cmd like "POLL/%" order by intr') ;
 	            if (_sizeof($list_crontab)) foreach($list_crontab as $rec)
 	            {
 	                $timetable=ENGINE()->crontab_get_timetable($rec['intr']);

 	                ?><tr>
 	                  <td><input type="checkbox" class="v2" cmd="aspmo_setting/change_cron_work_status" id="<?echo $rec['pkey']?>" cron_cmd="<?echo $rec['cmd']?>" <?if ($rec['enabled']) echo 'checked'?>></td>
 	                  <td><?echo ($rec['status'])? 'Выполняется':'Ожидает'?></td>
 	                  <td><?echo $timetable?> <a class="v2" cmd="aspmo_setting/edit_timetable" cron_id="<?echo $rec['pkey']?>" cron_name="<?echo $rec['obj_name']?>"><i class="fas fa-pencil-alt"></i></a>
 	                      <?if ($rec['default_intr']) echo '<p class="red">Рекомендуется:<br>'.$rec['default_intr'].'</p>'?>
 	                  </td>
 	                  <td class="left"><?echo $rec['obj_name']?></td>
 	                  <td><?echo ($rec['last_exec'])? date('d.m.Y H:i:s',$rec['last_exec']):'-'?></td>
 	                  <td><?echo ($rec['time_exec'])? $rec['time_exec'].'c.':'-'?></td>
 	                  <td><a href="/cab/setting/crontab/exec/<?echo $rec['pkey']?>/" target="_blank" cron_cmd="<?echo $rec['cmd']?>">Выполнить задание</a></td>
 	               </tr><?
 	            }
 	         ?>
 	     </table></form><br><br>
 	     <style>
 	         i.fas.fa-pencil-alt {font-size: 20px;float: right;}
 	         a {color: #2da5da;}
 	     </style>

 	     <?
 }

 function CMD_clear_poll_dubl_results()
   {
       $recs=execSQL('select personal_id,question_id,count(pkey) as cnt 
                      from poll_result
                      group by personal_id,question_id
                      having cnt>=2
                    ',0,1)  ;
       if (_sizeof($recs)) foreach($recs as $rec)
       {
           $recs_stats=execSQL('select pkey,c_data,personal_id,mo_id,event_id,pass_id,question_id,answer_id,correct,poll_id,answer_ball from poll_result where personal_id='.$rec['personal_id'].' and question_id='.$rec['question_id'].' order by pkey',2,1) ;
           if (_sizeof($recs_stats)>=2)
           { $arr_ids=[] ;
             foreach($recs_stats as $rec_stat) $arr_ids[]=$rec_stat['pkey'] ;
             unset($arr_ids[_sizeof($arr_ids)-1]) ;
             $str_ids=implode(',',$arr_ids) ;
             execSQL_update('delete from poll_result where pkey in ('.$str_ids.')') ;
             echo 'Удалена запись ID '.$str_ids.'<br>' ;
		   }

	   }


	 }


 function CMD_clear_poll_space_results()
 {
    execSQL_update('delete from poll_result where personal_id=0',array('debug'=>2)) ;
    execSQL_update('delete from poll_result where answer_id=0 and answer_ball=0',array('debug'=>2)) ;
 }


 function CMD_sync_poll_result_to_poll_sessions()
 {

     $recs=execSQL('select t1.*,
                    t3.terminal_pkey,t3.terminal_id,t3.member_id as personal_id,t3.group_id,t3.reader,t3.c_data,t3.e_data,t3.reason,t3.equipment,t3.video,t3.DTW_id,
                    t3.c_data_m,t3.c_data_h,t3.c_data_d, t3.error,t3.error_reason,t3.message_terminal,t3.terminal_comment
                    from poll_result t1
                    left join poll_sessions t2 on  t2.mo_id=t1.mo_id
                    left join obj_site_mo_session t3 on  t3.pkey=t1.mo_id
                    where t2.pkey is null and t1.mo_id>0
                   ',2) ;
     if (!_sizeof($recs)) return ;
     return ;
     echo 'Найдено <strong>'._sizeof($recs).'</strong> записей в poll_result, сессии которых отсутстуют в poll_sessions<br>' ;
     $recs_mo=group_by_field('mo_id',$recs) ;
     if (_sizeof($recs_mo)) foreach($recs_mo as $mo_id=>$poll_results)
     {
         $mo_info=$poll_results[0] ;
         $rec_session_kz=array('mo_id'          => $mo_id,
                               'DTW_id'        => $mo_info['DTW_id'],
                               'pass_id'        => $mo_info['pass_id'],
                               'terminal_id'    => $mo_info['terminal_id'],
                               'terminal_pkey'  => $mo_info['terminal_pkey'],
                               'personal_id'    => $mo_info['personal_id'],
                               'group_id'       => $mo_info['group_id'],
                               'reader'         => ($mo_info['reader'])? $mo_info['reader']:'',
                                'c_data'        => $mo_info['c_data'],
                                'e_data'        => $mo_info['e_data'],
                                'c_data_m'        => $mo_info['c_data_m'],
                                'c_data_h'        => $mo_info['c_data_h'],
                                'c_data_d'        => $mo_info['c_data_d'],
                 	            'reason'        => $mo_info['reason'],
                 	            'equipment'     => $mo_info['equipment'],
                 	            'video'         => $mo_info['video'],
                 	            'error'         => $mo_info['error'],
                 	            'error_reason'         => $mo_info['error_reason'],
                 	            'message_terminal'         => $mo_info['message_terminal'],
                 	            'terminal_comment'         => $mo_info['terminal_comment'],
                 	            'status'         => 2,
                 	            'clss'         => 578,
                 	            'indx'         => 1
                               //'pass_id'        => $rec_event_pass['event_pass_id']
                              );
         multiSQL_insert('poll_sessions')->append($rec_session_kz);
         $arr_sessions[]=$rec_session_kz ;
     }

     //print_2x_arr($arr_sessions);
     multiSQL_insert('poll_sessions')->flush();

     execSQL_update('update poll_result t1
                     right join poll_sessions t2 on t2.mo_id=t1.mo_id
                     set t1.poll_id=t2.pkey
                     where (t1.poll_id=0 or t1.poll_id is null)'
                    ,2) ;




 }

  function CMD_clear_poll_bag_results()
  {
         execSQL_update('delete from poll_sessions_questions where parent in (select pkey from poll_sessions where event_id=298)',['debug'=>2]) ;

         execSQL_update('delete from poll_sessions where event_id=298',['debug'=>2]) ;

         execSQL_update('delete from poll_sessions_questions where parent in (select pkey from poll_sessions where personal_id=0)',['debug'=>2]) ;

         execSQL_update('delete from poll_sessions where personal_id=0',['debug'=>2]) ;
  }





}

?>
