<?php

/*
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                     Чат v.:6.0 для JohnCMS v.:4.3.x                        //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                               Автор: k_2                                   //
//                                                                            //
//                Благодарности выражать на: WMR 250322967425.                //
//                                                                            //
//                     Обратная связь: k2022@rambler.ru                       //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
*/

defined('_IN_JOHNCMS') or die('Error: restricted access');

// Проверяем права доступа
if ($rights < 9) {
  header("Location: $home?err");
 exit;
}

echo '<div class="phdr"><a href="../' . $set['admp'] . '/index.php"><b>' . $lng['admin_panel'] . '</b></a> | '.$lng_chat['control_rooms'].'</div>';
switch ($mod) {

  case 'delete' :
    /*
    -----------------------------------------------------------------
    Удаление комнаты
    -----------------------------------------------------------------
    */
    if (!$id) {
      echo '<div class="rmenu"><b>' . $lng['error'] . '</b><p><a href="?act=mod_rooms">' . $lng['back'] . '</a></p></div>';
      echo '<div class="phdr"><a href="menu.php">' . $lng_chat['menu'] . '</a></div>';
      require('../incfiles/end.php');
     exit;
    }
    $k_d = mysql_fetch_assoc(mysql_query("SELECT `name` FROM `chat_rooms` WHERE `id` = '" . $id . "'"));
    if (isset ($_GET['yes'])) {
      mysql_query("DELETE FROM `chat_rooms` WHERE `id` = '" . $id . "'");
      mysql_query("DROP TABLE IF EXISTS `chat_room_".$id."`");
      mysql_query("OPTIMIZE TABLE `chat_rooms`");
      header("Location: ?act=mod_rooms&do=k_del");
    } else {
      echo '<div class="rmenu">'.$lng_chat['really_delete_rooms'].' <b>'.$k_d['name'].'</b>?<p><a href="?act=mod_rooms&amp;mod=delete&amp;id='.$id.'&amp;yes">'.$lng_chat['action_yes'].'</a> | <a href="?act=mod_rooms">'.$lng_chat['action_no'].'</a></p></div>';
      echo '<div class="phdr"><a href="?act=mod_rooms">'.$lng['back'].'</a></div>';

    }
  break;

  case 'add' :
    /*
    -----------------------------------------------------------------
    Добавление комнаты
    -----------------------------------------------------------------
    */
    if (isset ($_POST['submit'])) {
      // Сохранение данных
      if ((empty ($_POST['tr'])) && (empty ($_POST['nr']))) {
        echo functions::display_error($lng_chat['not_enter_room_name'], '<a href="menu.php?act=mod_rooms&amp;mod=add">' . $lng['back'] . '</a>');
        echo '<div class="phdr"><a href="menu.php">'.$lng_chat['menu'].'</a></div>';
        require('../incfiles/end.php');
       exit;
      }
      $id_bot = isset($_POST['bot']) ? $_POST['bot'] : '';    
      if ($id_bot) {
      $id_mass = array ();
      foreach ($id_bot as $val) {
        $id_mass[] = intval($val);
      }
      $bot = serialize($id_mass);
      } else {
      $bot = 0;
      }
      $name_room = isset($_POST['nr']) ? functions::check(mb_substr($_POST['nr'], 0, 50)) : '';
      $op = isset($_POST['op']) ? trim(mb_substr($_POST['op'], 0, 500)) : '';
      $tr = functions::check($_POST['tr']);
      $nev = trim($_POST['nev']);
      // Задаём значения в зависимости от типа комнаты 
      if (!$tr) {
        if (!$name_room)
          $name_room = 'room';
      } elseif ($tr == 'in') {
        if (!$name_room)
          $name_room = $lng_chat['intimately'];
        $bot = 0;
      } elseif ($tr == 'sr' && !$name_room) {
        $name_room = $lng_chat['lawlessness'];
      } elseif ($tr == 'an') {
        if (!$name_room)  
          $name_room = $lng_chat['incognito'];
        $bot = 0;
      }
      // Проверка на то, что комната с таким именем несуществует
      $room_and_name = mysql_query("SELECT `name` FROM `chat_rooms` WHERE `name` = '".$name_room."'");
      if (mysql_num_rows($room_and_name)) { 
        header("location: menu.php?act=mod_rooms&do=error");
       exit;
      }
      // Заносим данные в б.д.
      mysql_query("INSERT INTO `chat_rooms` SET
        `name` = '".mysql_real_escape_string($name_room)."',
        `op` = '".mysql_real_escape_string($op)."',
        `tip` = '".mysql_real_escape_string($tr)."',
        `bot` = '".mysql_real_escape_string($bot)."',
        `nev` = '".mysql_real_escape_string($nev)."'
      ");
      $room_id = mysql_insert_id();
      mysql_query("DROP TABLE IF EXISTS `chat_room_".$room_id."`");
      mysql_query("CREATE TABLE `chat_room_".$room_id."` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `id_u` int(11) NOT NULL,
        `id_s` int(11) NOT NULL,
        `id_bot` int(11) NOT NULL,
        `time` int(15) NOT NULL,
        `text` text NOT NULL,
        `author` text NOT NULL,
        `tip` int(1) NOT NULL,
        `pas` text NOT NULL,
         PRIMARY KEY (`id`)
         ) ENGINE=MyISAM DEFAULT CHARSET=utf8
      ");
      header("Location: ?act=mod_rooms&do=k_dob");
    } else {
      // Ввод данных
      echo '<form action="?act=mod_rooms&amp;mod=add" method="post">';
      echo '<div class="menu"><p><h3><img src="img/room_plus.png" width="16" height="16" class="left" />&#160;'.$lng_chat['adding_a_room'].'</h3>';
      $a1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'in'"), 0);
      $b1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'sr'"), 0);
      $с1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'an'"), 0);
      if (!$a1 || !$b1 || !$с1) {
        echo '&#160;'.$lng_chat['room_type'].':<br />&#160;<select name="tr"><option value="">'.$lng_chat['simple'].'</option>';
        if (!$a1)
          echo '<option value="in">'.$lng_chat['intimately'].'</option>';
        if (!$b1)
          echo '<option value="sr">'.$lng_chat['lawlessness'].'</option>';
        if (!$с1)
          echo '<option value="an">'.$lng_chat['incognito'].'</option>';
        echo '</select><br />';
      }
      echo '&#160;'.$lng_chat['name_if_a_simple'].':<br />&#160;<input type="text" name="nr"/></p>';           
      echo '<p><h3><img src="img/options_plus.png" width="16" height="16" class="left" />&#160;'.$lng_chat['more_options'].'</h3>';
      echo '&#160;'.$lng['description'].':<br />&#160;<textarea rows="' . $set_user['field_h'] . '" name="op">'.htmlentities($ms['op'], ENT_QUOTES, 'UTF-8').'</textarea><br />';
      echo '&#160;'.$lng_chat['hello_user'].':<br />&#160;<textarea rows="' . $set_user['field_h'] . '" name="nev">'.htmlentities($ms['nev'], ENT_QUOTES, 'UTF-8').'</textarea><br />';
      echo '<small>&#160;&#160;<span style="color:blue">[login]</span> - '.$lng_chat['login_user'].'<br />';
      echo '&#160;&#160;'.$lng_chat['faq_m_j'].'</small></p>';
      $bot = mysql_query("SELECT `id`, `name` FROM `chat_bot`");
      if (mysql_num_rows($bot)) {
        echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left" />&#160;'.$lng_chat['bots'].'</h3>';
        while ($bot_d = mysql_fetch_assoc($bot)) {
          echo '&#160;<input type="checkbox" name="bot[]" value="'.$bot_d['id'].'"/> '.$bot_d['name'].'<br />'; 
        }
        echo '<small>&#160;&#160;'.$lng_chat['room_bot_info'].'</small></p>';
      }
      echo '<p><input type="submit" name="submit" value="'.$lng['save'].'"/></p>';
      echo '</div></form>';
      echo '<div class="phdr"><a href="?act=mod_rooms">'.$lng['back'].'</a></div>';
    }
  break;

  case 'edit' :
    /*
    -----------------------------------------------------------------
    Редактирование комнаты
    -----------------------------------------------------------------
    */
    if (!$id) {
      header("location: menu.php?act=mod_rooms&do=error");
     exit;
    }
    $typ = mysql_query("SELECT * FROM `chat_rooms` WHERE `id` = '" . $id . "'");
    // Проверка на существование комнаты
    if (!mysql_num_rows($typ)) { 
      header("location: menu.php?act=mod_rooms&do=error");
     exit;
    }
    $ms = mysql_fetch_array($typ);
    if (isset ($_POST['submit'])) {
      // Сохраняем данные
      if ((empty ($_POST['tr'])) && (empty ($_POST['nr']))) {
        echo functions::display_error($lng_chat['not_enter_room_name'], '<a href="menu.php?act=mod_rooms&amp;mod=edit&amp;id=' . $id . '">' . $lng['back'] . '</a>');
        echo '<div class="phdr"><a href="menu.php">'.$lng_chat['menu'].'</a></div>';
        require("../incfiles/end.php");
       exit;
      }
      $id_bot = isset($_POST['bot']) ? $_POST['bot'] : '';    
      if ($id_bot) {
      $id_mass = array ();
      foreach ($id_bot as $val) {
        $id_mass[] = intval($val);
      }
      $bot = serialize($id_mass);
      } else {
      $bot = 0;
      }
      $name_room = isset($_POST['nr']) ? functions::check(mb_substr($_POST['nr'], 0, 50)) : '';
      $op = isset($_POST['op']) ? trim(mb_substr($_POST['op'], 0, 500)) : '';
      $tr = isset($_POST['tr']) ? trim($_POST['tr']) : '';
      $nev = trim($_POST['nev']);
      // Задаём значения в зависимости от типа комнаты 
      if (!$tr) {
        if (!$name_room)
          $name_room = 'room';
      } elseif ($tr == 'in') {
        if (!$name_room)
          $name_room = $lng_chat['intimately'];
        $bot = 0;
      } elseif ($tr == 'sr' && !$name_room) {
        $name_room = $lng_chat['lawlessness'];
      } elseif ($tr == 'an') {
        if (!$name_room)  
          $name_room = $lng_chat['incognito'];
        $bot = 0;
      }
      if ($ms['tip'] && ($tr != $ms['tip'] || !$tr)) {
        mysql_query("DELETE FROM `chat_room_".$id."`");
        mysql_query("OPTIMIZE TABLE `chat_room_".$id."`");
      }
      // Изменяем данные в б.д.
      mysql_query("update `chat_rooms` set `name` = '".mysql_real_escape_string($name_room)."', `op` = '".mysql_real_escape_string($op)."', `tip` = '".mysql_real_escape_string($tr)."', `bot` = '".mysql_real_escape_string($bot)."', `nev` = '".mysql_real_escape_string($nev)."' where `id` = '".$id."'");
      header("Location: ?act=mod_rooms&do=k_izm");
    } else {
      // Изменяем данные
      echo '<form action="?act=mod_rooms&amp;mod=edit&amp;id=' . $id . '" method="post">';
      echo '<div class="menu"><p><h3><img src="img/room_edit.png" width="16" height="16" class="left" />&#160;'.$lng_chat['changing_rooms'].'</h3>';      
      $a1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'in'"), 0);
      $b1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'sr'"), 0);
      $c1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms` WHERE `tip` = 'an'"), 0);
      if (!$a1 || !$b1 || !$c1 || $ms['tip']) {
        echo '&#160;'.$lng_chat['room_type'].':<br />&#160;<select name="tr">';
        echo '<option value="0"'.(!$ms['tip'] ? ' selected="selected"' : '').'>'.$lng_chat['simple'].'</option>';
        if (!$b1 || $ms['tip']=='sr')
          echo '<option value="sr"'.($ms['tip']=='sr' ? ' selected="selected"' : '').'>'.$lng_chat['lawlessness'].'</option>';
        if (!$a1 || $ms['tip']=='in')
          echo '<option value="in"'.($ms['tip']=='in' ? ' selected="selected"' : '').'>'.$lng_chat['intimately'].'</option>';
        if (!$c1 || $ms['tip']=='an')
          echo '<option value="an"'.($ms['tip']=='an' ? ' selected="selected"' : '').'>'.$lng_chat['incognito'].'</option>';
        echo '</select><br />';
      }
      echo '&#160;'.$lng_chat['name_if_a_simple'].':<br />&#160;<input type="text" name="nr" value="' . $ms['name'] . '"/></p>';
      echo '<p><h3><img src="img/options_edit.png" width="16" height="16" class="left" />&#160;'.$lng_chat['more_options'].'</h3>';
      echo '&#160;'.$lng['description'].':<br />&#160;<textarea rows="' . $set_user['field_h'] . '" name="op">'.htmlentities($ms['op'], ENT_QUOTES, 'UTF-8').'</textarea><br />';
      echo '&#160;'.$lng_chat['hello_user'].':<br />&#160;<textarea rows="' . $set_user['field_h'] . '" name="nev">'.htmlentities($ms['nev'], ENT_QUOTES, 'UTF-8').'</textarea><br />';
      echo '<small>&#160;&#160;<span style="color:blue">[login]</span> - '.$lng_chat['login_user'].'<br />';
      echo '&#160;&#160;'.$lng_chat['faq_m_j'].'</small></p>';
      $bot = mysql_query("SELECT `id`, `name` FROM `chat_bot`");
      if (mysql_num_rows($bot)) {
        $bot_m = unserialize($ms['bot']);
        echo '<p><h3><img src="img/bot.png" width="16" height="16" class="left" />&#160;'.$lng_chat['bots'].'</h3>';
        while ($bot_d = mysql_fetch_assoc($bot)) {
          echo '&#160;<input type="checkbox" name="bot[]" value="'.$bot_d['id'].'" '.($bot_m ? (in_array($bot_d['id'], $bot_m) ? ' checked="checked"' : '') : '').'/> '.$bot_d['name'].'<br />'; 
        }
        echo '<small>&#160;&#160;'.$lng_chat['room_bot_info'].'</small></p>';
      }      
      echo '<p><input type="submit" name="submit" value="'.$lng['save'].'"/></p>';
      echo '</div></form>';
    }
    echo '<div class="phdr"><a href="?act=mod_rooms">'.$lng['back'].'</a></div>';
  break;

  case 'up' :
    /*
    -----------------------------------------------------------------
    Перемещение комнаты на одну позицию вверх
    -----------------------------------------------------------------
    */
    if ($id) {
      $req = mysql_query("SELECT `name`, `op`, `tip`, `bot`, `nev` FROM `chat_rooms` WHERE `id` = '$id' LIMIT 1");
      if (mysql_num_rows($req)) {
        $res = mysql_fetch_assoc($req);
        $req2 = mysql_query("SELECT `id`, `name`, `op`, `tip`, `bot`, `nev` FROM `chat_rooms` WHERE `id` < '$id' ORDER BY `id` DESC LIMIT 1");
        if (mysql_num_rows($req2)) {
          $res2 = mysql_fetch_assoc($req2);
          mysql_query("UPDATE `chat_rooms` SET `name` = '".mysql_real_escape_string($res2['name'])."', `op` = '".mysql_real_escape_string($res2['op'])."', `tip` = '".mysql_real_escape_string($res2['tip'])."', `bot` = '".mysql_real_escape_string($res2['bot'])."', `nev` = '".mysql_real_escape_string($res2['nev'])."' WHERE `id` = '$id'");
          mysql_query("UPDATE `chat_rooms` SET `name` = '".mysql_real_escape_string($res['name'])."', `op` = '".mysql_real_escape_string($res['op'])."', `tip` = '".mysql_real_escape_string($res['tip'])."', `bot` = '".mysql_real_escape_string($res['bot'])."', `nev` = '".mysql_real_escape_string($res['nev'])."' WHERE `id` = '".$res2['id']."'");
          mysql_query("DELETE FROM `chat_room_".$id."`");
          mysql_query("DELETE FROM `chat_room_".$res2['id']."`");
          mysql_query("OPTIMIZE TABLE `chat_room_".$id."`");
          mysql_query("OPTIMIZE TABLE `chat_room_".$res2['id']."`");
        }
      }
    }
    header("Location: ?act=mod_rooms&do=k_ver");
  break;

  case 'down' :
    /*
    -----------------------------------------------------------------
    Перемещение комнаты на одну позицию вниз
    -----------------------------------------------------------------
    */
    if ($id) {
      $req = mysql_query("SELECT `name`, `op`, `tip`, `bot`, `nev` FROM `chat_rooms` WHERE `id` = '$id' LIMIT 1");
      if (mysql_num_rows($req)) {
        $res = mysql_fetch_assoc($req);
        $req2 = mysql_query("SELECT `id`, `name`, `op`, `tip`, `bot`, `nev` FROM `chat_rooms` WHERE `id` > '$id' LIMIT 1");
        if (mysql_num_rows($req2)) {
          $res2 = mysql_fetch_assoc($req2);
          mysql_query("UPDATE `chat_rooms` SET `name` = '".mysql_real_escape_string($res2['name'])."', `op` = '".mysql_real_escape_string($res2['op'])."', `tip` = '".mysql_real_escape_string($res2['tip'])."', `bot` = '".mysql_real_escape_string($res2['bot'])."', `nev` = '".mysql_real_escape_string($res2['nev'])."' WHERE `id` = '$id'");
          mysql_query("UPDATE `chat_rooms` SET `name` = '".mysql_real_escape_string($res['name'])."', `op` = '".mysql_real_escape_string($res['op'])."', `tip` = '".mysql_real_escape_string($res['tip'])."', `bot` = '".mysql_real_escape_string($res['bot'])."', `nev` = '".mysql_real_escape_string($res['nev'])."' WHERE `id` = '".$res2['id']."'");
          mysql_query("DELETE FROM `chat_room_".$id."`");
          mysql_query("DELETE FROM `chat_room_".$res2['id']."`");
          mysql_query("OPTIMIZE TABLE `chat_room_".$id."`");
          mysql_query("OPTIMIZE TABLE `chat_room_".$res2['id']."`");
        }
      }
    }
    header("Location: ?act=mod_rooms&do=k_vn");
  break;

  default :
    /*
    -----------------------------------------------------------------
    Список комнат Чата
    -----------------------------------------------------------------
    */
    switch ($do) {

      case 'k_vn':
        echo '<div class="gmenu"><b>'.$lng_chat['the_room_is_down'].'</b></div>';
      break;
    
      case 'k_ver':
        echo '<div class="gmenu"><b>'.$lng_chat['the_room_is_raised_up'].'</b></div>';
      break;
    
      case 'k_izm':
        echo '<div class="gmenu"><b>'.$lng_chat['room_changed'].'</b></div>';
      break;
    
      case 'k_dob':
        echo '<div class="gmenu"><b>'.$lng_chat['room_added'].'</b></div>';
      break;
    
      case 'k_del':
        echo '<div class="gmenu"><b>'.$lng_chat['room_deleted'].'</b></div>';
      break;
    
      case 'error':
        echo '<div class="rmenu"><b>'.$lng['error'].'</b></div>';
      break;
    
      default :
        echo '';
    }
    $i=0;
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_rooms`"), 0);
    $req = mysql_query("SELECT `id`, `name`, `op` FROM `chat_rooms`");
    while ($res = mysql_fetch_assoc($req)) {
      echo ($i % 2) ? '<div class="list2">' : '<div class="list1">';
      echo '<b>' . $res['name'] . '</b><div class="sub">';
      if (!empty($res['op']))
        echo '<span class="gray">' . functions::checkout($res['op'], 1, 0)  . '</span><br />';
      if ($i)
        echo '<a href="?act=mod_rooms&amp;mod=up&amp;id=' . $res['id'] . '">'.$lng_chat['up'].'</a> | ';
      if ($i < ($total-1))
        echo '<a href="?act=mod_rooms&amp;mod=down&amp;id=' . $res['id'] . '">'.$lng_chat['down'].'</a> | ';
      echo '<a href="?act=mod_rooms&amp;mod=edit&amp;id=' . $res['id'] . '">'.$lng_chat['rev'].'</a> | ';
      echo '<a href="?act=mod_rooms&amp;mod=delete&amp;id=' . $res['id'] . '">'.$lng['delete'].'</a></div></div>';
     ++$i;
    }
    echo '<div class="gmenu"><form action="?act=mod_rooms&amp;mod=add" method="post"><input type="submit" value="'.$lng_chat['add_room'].'" /></form></div>';
    echo '<div class="phdr"><a href="../chat/index.php">'.$lng_chat['to_chat'].'</a></div>';
}
echo '<p><a href="menu.php">'.$lng_chat['menu'].'</a><br /><a href="../' . $set['admp'] . '/index.php">'.$lng['admin_panel'].'</a></p>';

?>