<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
class c_page_ajax extends c_page_XML_AJAX
{

  function explain_sql()
  {  ?><div style="margin:10px 0 0 20px;"><?
     $sql=base64_decode($_POST['sql']) ;
     $sql_text=$sql ;
     $sql_text=str_ireplace('from','<br>from',$sql_text) ;
     $sql_text=str_ireplace('where','<br>where',$sql_text) ;
     $sql_text=str_ireplace('order','<br>order',$sql_text) ;
     $sql_text=str_ireplace('limit','<br>limit',$sql_text) ;
     echo $sql_text ;
     $recs=execSQL('explain '.$sql) ;
     print_2x_arr($recs) ;
     $this->add_element('show_modal_window','HTML',array('title'=>'Explain SQL','width'=>'1000px')) ;
     ?></div><?

  }


  // создаем резервную копию таблицы БД, передаем код таблицы, имя таблицы или используется obj_info
  function create_res_copy_db_table()
  { include(_DIR_TO_MODULES.'/engine/i_table.php') ;
    $table_id=(int)$_POST['table_id'] ;
    if (_DOT($table_id)!==null)
    {
        TABLE(_DOT($table_id)->table_name)->create_res_copy() ;
        $this->add_element('show_modal_window','HTML',array('title'=>'create_res_copy','width'=>'1000px')) ;
        ?><div class="center"><button class="cancel">Закрыть</button></div><?
    }
  }


  function table_convert_clss()
  { include(_DIR_TO_MODULES.'/engine/i_table.php') ;
    $table_id=(int)$_POST['table_id'] ;
    if (_DOT($table_id)!==null)
    {
        TABLE(_DOT($table_id)->table_name)->convert_clss() ;
        $this->add_element('show_modal_window','HTML',array('title'=>'table_convert_clss','width'=>'1000px')) ;
        ?><div class="center"><button class="cancel">Закрыть</button></div><?
    }
  }
  function table_convert_clss_to_id()
  { include(_DIR_TO_MODULES.'/engine/i_table.php') ;
    $table_id=(int)$_POST['table_id'] ;
    if (_DOT($table_id)!==null)
    {
        TABLE(_DOT($table_id)->table_name)->table_convert_clss_to_id() ;
        $this->add_element('show_modal_window','HTML',array('title'=>'table_convert_clss_to_id','width'=>'1000px')) ;
        ?><div class="center"><button class="cancel">Закрыть</button></div><?
    }
  }

  // выполнят набор команд к базе данных, хранящихся в массиве $_POST['sql_cmd']
  function exec_sql_list_cmd()
  {  if (_ENGINE_DEMO_MODE) {?><div class=alert>Включен режим работы "только чтение", изменения запрещены</div><? return ; }
     damp_array($_POST,1,-1) ;
     if ($_POST['uid']) $arr_sql_actions=ENGINE()->load_temp_setting($_POST['uid']) ;
     if (sizeof($_POST['sql_cmd'])) $arr_sql_actions=$_POST['sql_cmd'] ;
     damp_array($arr_sql_actions,1,-1);


/*     if (_sizeof($_POST['sql_cmd'])) foreach ($_POST['sql_cmd'] as $uid=>$enabled) if (isset($arr_sql_actions[$uid])) // идем по списку отмеченных операций
      { $sql=$arr_sql_actions[$uid] ;
        echo $sql.' - <span class=green>ok</span><br>' ;
        //execSQL_update($sql) ;
      }
*/
     if (_sizeof($_POST['sql_cmd'])) foreach ($_POST['sql_cmd'] as $sql) //if (isset($arr_sql_actions[$uid])) // идем по списку отмеченных операций
      { //$sql=$arr_sql_actions[$uid] ;
        echo $sql.' - <span class=green>ok</span><br>' ;
        execSQL_update($sql) ;
      }
     echo '<strong class=green>Все операции выполнены</strong><br>' ;
     ?><div class="center"><button class="btn btn-success cancel">Закрыть</button></div><?
     $this->add_element('show_modal_window','HTML',array('title'=>'Исправление таблицы','width'=>'700px','after_close_update_page'=>1)) ;

  }

  function delete_temp_tables()
  {
      $recs_table=execSQL('
             SELECT TABLE_NAME,TABLE_TYPE,ENGINE,TABLE_COLLATION
             FROM information_schema.TABLES 
             WHERE table_schema = "'.$GLOBALS['_SETTING']['main_db']['db_name'].'" and (TABLE_NAME like "temp_%" or TABLE_NAME like "delete_%")');
      ?><div style="height:500px;overflow:auto"><?
      print_2x_arr($recs_table);
      ?></div><?
      ?><button class="button v2" cmd="db/delete_temp_tables_apply">Удалить <?echo _sizeof($recs_table)?> временнных таблиц</button><?
      $this->add_element('show_modal_window','HTML',array('title'=>'Удаление временных таблиц','width'=>'1000px')) ;
  }

  function delete_temp_tables_apply()
  {
      $recs_table=execSQL('
               SELECT TABLE_NAME,TABLE_TYPE,ENGINE,TABLE_COLLATION
               FROM information_schema.TABLES 
               WHERE table_schema = "'.$GLOBALS['_SETTING']['main_db']['db_name'].'" and (TABLE_NAME like "temp_%" or TABLE_NAME like "delete_%")');
        ?><div style="height:500px;overflow:auto"><?
        if (_sizeof($recs_table)) foreach($recs_table as $rec)
        { ob_start() ;
          execSQL_update('drop table '.$rec['TABLE_NAME'],array('debug'=>0)) ;
          $text=ob_get_clean() ;
          if (preg_match('/Ошибка при отработке SQL запроса/is',$text)) $result='<span class="red">ERROR</span><br>'.$text ;
          else $result='<span class="green">OK</span>' ;
          echo 'Удаление таблицы "<strong>'.$rec['TABLE_NAME'].'</strong>" - '.$result.'<br>' ;
        }
        ?></div><?
        ?><button class="button cancel">Закрыть</button><?
        $this->add_element('show_modal_window','HTML',array('title'=>'Удаление временных таблиц','width'=>'1000px','after_close_update_page'=>1)) ;
  }

  function delete_view_personals()
  {
      //$tt='TABLE_NAME like "view_personals_account%" or TABLE_NAME like "view_personals_event%" or TABLE_NAME like "view_personals_group%" or  TABLE_NAME like "view_personals_poll%" or TABLE_NAME like "view_personals_quiz%" or  TABLE_NAME like "view_personals_workgroup%"' ;
      $tt='TABLE_NAME like "view_personals_event%" or TABLE_NAME like "view_personals_poll%" or TABLE_NAME like "view_personals_quiz%"' ;
      $recs_table=execSQL('
             SELECT TABLE_NAME,TABLE_TYPE,ENGINE,TABLE_COLLATION
             FROM information_schema.TABLES 
             WHERE table_schema = "'.$GLOBALS['_SETTING']['main_db']['db_name'].'" and ('.$tt.')');
      ?><div style="height:500px;overflow:auto"><?
      print_2x_arr($recs_table);
      ?></div><?
      ?><button class="button v2" cmd="db/delete_view_personals_apply">Удалить <?echo _sizeof($recs_table)?> вьюверов сотрудников</button><?
      $this->add_element('show_modal_window','HTML',array('title'=>'Удаление вьюверов сотрудников','width'=>'1000px')) ;
  }

  function delete_view_personals_apply()
  {   //$tt='TABLE_NAME like "view_personals_account%" or TABLE_NAME like "view_personals_event%" or TABLE_NAME like "view_personals_group%" or  TABLE_NAME like "view_personals_poll%" or TABLE_NAME like "view_personals_quiz%" or  TABLE_NAME like "view_personals_workgroup%"' ;
      $tt='TABLE_NAME like "view_personals_event%" or TABLE_NAME like "view_personals_poll%" or TABLE_NAME like "view_personals_quiz%"' ;
      $recs_table=execSQL('
             SELECT TABLE_NAME,TABLE_TYPE,ENGINE,TABLE_COLLATION
             FROM information_schema.TABLES 
             WHERE table_schema = "'.$GLOBALS['_SETTING']['main_db']['db_name'].'" and ('.$tt.')');
        ?><div style="height:500px;overflow:auto"><?
        if (_sizeof($recs_table)) foreach($recs_table as $rec)
        { ob_start() ;
          if ($rec['TABLE_TYPE']=='VIEW') execSQL_update('drop view '.$rec['TABLE_NAME'],array('debug'=>0)) ;
          else                            execSQL_update('drop table '.$rec['TABLE_NAME'],array('debug'=>0)) ;
          $text=ob_get_clean() ;
          if (preg_match('/Ошибка при отработке SQL запроса/is',$text)) $result='<span class="red">ERROR</span><br>'.$text ;
          else $result='<span class="green">OK</span>' ;
          echo 'Удаление таблицы "<strong>'.$rec['TABLE_NAME'].'</strong>" - '.$result.'<br>' ;
        }
        ?></div><?
        ?><button class="button cancel">Закрыть</button><?
        $this->add_element('show_modal_window','HTML',array('title'=>'Удаление вьюверов сотрудников','width'=>'1000px','after_close_update_page'=>1)) ;
  }

}
