<?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;
}

if ($mod == 'red' || $mod == 'dell') {
  $req = mysql_query("SELECT `id_bot`, `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $id . "'");
  if (!mysql_num_rows($req)) { 
    header("Location: menu.php?act=mod_bots&do=error");
   exit;
  }
  $res = mysql_fetch_assoc($req);
  $id_b = $res['id_bot'];
} else {
  $id_b = $id;  
}
$bot = mysql_query("SELECT `name`, `tip` FROM `chat_bot` WHERE `id` = '" . $id_b . "'");
// Проверка на существование бота.
if (!mysql_num_rows($bot)) { 
  header("Location: menu.php?act=mod_bots&do=error");
 exit;
}
// Получение данных бота.
$bot_d = mysql_fetch_assoc($bot); 

switch ($mod) {

  case 'red':
    /*
    -----------------------------------------------------------------
    Редактирование фразы
    -----------------------------------------------------------------
    */ 
    echo '<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id_b.'"><b>' . $lng_chat['phrases'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['editing_phrase'].'</div>';
    if (isset ($_GET['red_yes'])) {
      $vopros = trim($_POST['vopros'],0);
      $otvet = isset($bot_d['tip']) ? trim($_POST['otvet']) : 0;
      if (empty($vopros) || empty($otvet) && $bot_d['tip']) {
        echo '<div class="rmenu"><p><b>'.$lng['error'].'</b><br />' . $lng['error_empty_fields'] . '</p></div>';
      } else {
        $result = mysql_query("UPDATE `chat_vop` SET `vopros` = '" . mysql_real_escape_string($vopros) . "',`otvet` = '" . mysql_real_escape_string($otvet) . "' WHERE `id` = '" . $id . "'");
        if ($result) {
          // Редактирование прошло успешно
          header("location: ?act=mod_phrases&id=$id_b&start=$start&do=f_i");
         exit;
        } else {
          // Произошла ошибка редактирования
          header("location: ?act=mod_phrases&id=$id_b&start=$start&do=f_ne_i");
         exit;
        }
      }
    } else {
      echo '<div class="gmenu"><b>'.$lng_chat['editing_phrase'].':</b></div>';
      echo '<form name="form" action="?act=mod_phrases&amp;mod=red&amp;id='.$id.'&amp;red_yes&amp;start='.$start.'" method="POST">';
      echo '<div class="menu"><h3>'.$lng_chat['phrase'].($bot_d['tip'] == 4 ? '*' : '').'</h3>';   
      echo '<textarea rows="' . $set_user['field_h'] . '" name="vopros">'.htmlentities($res['vopros'], ENT_QUOTES, 'UTF-8').'</textarea></div>';
      if ($bot_d['tip']) {
        echo '<div class="menu"><h3>'.$lng_chat['reply'].($bot_d['tip'] == 4 ? '*' : '').'</h3>';
        echo '<textarea rows="' . $set_user['field_h'] . '" name="otvet">'.htmlentities($res['otvet'], ENT_QUOTES, 'UTF-8').'</textarea></div>';
      }
      if ($bot_d['tip'] == 4)
        echo '<div class="menu">*<small>&#160;&#160;'.$lng_chat['faq_f_mass'].'</small></div>';
      echo '<div class="gmenu"><input type="submit" name="" value="'.$lng['save'].'" />';
      echo '</div></form>';
    }
 break;

  case 'delete':
    /*
    -----------------------------------------------------------------
    Удаление всех фраз бота
    -----------------------------------------------------------------
    */ 
    if (isset ($_GET['yes'])) {
      mysql_query("DELETE FROM `chat_vop` WHERE `id_bot` = '" . $id . "'");
      mysql_query("OPTIMIZE TABLE `chat_vop`");
      header("location: ?act=mod_phrases&id=$id&do=s_o");
     exit;
    } else {
      echo '<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id.'"><b>' . $lng_chat['phrases'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['clear_list_of_phrases'].'</div>';
      echo '<div class="rmenu">'.$lng_chat['clear_list_of_phrases_bot'].'';
      echo '<p><a href="?act=mod_phrases&amp;mod=delete&amp;id='.$id.'&amp;yes">'.$lng_chat['action_yes'].'</a> | <a href="?act=mod_phrases&amp;id='.$id_b.'&amp;start=' . $start . '">'.$lng_chat['action_no'].'</a></p></div>';
    }
 break;

  case 'massdel':
    /*
    -----------------------------------------------------------------
    Массовое удаление фраз
    -----------------------------------------------------------------
    */ 
    if (isset ($_GET['yes'])) {
      $dc = $_SESSION['dc'];
      foreach ($dc as $delid) {
        mysql_query("DELETE FROM `chat_vop` WHERE `id` = '" . intval($delid) . "' AND `id_bot` = '" . $id . "'");
      }
      header("location: ?act=mod_phrases&id=$id&do=o_f_u");
         exit;
    } else {
      echo '<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id.'"><b>' . $lng_chat['phrases'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['mass_removal'].'</div>';
      if (empty ($_POST['delch'])) {
        header("location: ?act=mod_phrases&id=$id");
      } else {
      foreach ($_POST['delch'] as $v) {
        $dc[] = intval($v);
      }
      $_SESSION['dc'] = $dc;
      echo '<div class="rmenu">'.$lng_chat['are_you_sure_to_remove'].'<p><a href="?act=mod_phrases&amp;id='.$id.'&amp;mod=massdel&amp;yes">'.$lng_chat['action_yes'].'</a> | <a href="?act=mod_phrases&amp;id='.$id_b.'&amp;start=' . $start . '">'.$lng_chat['action_no'].'</a></p></div>';
      }
    }
 break;

  case 'dell':
    /*
    -----------------------------------------------------------------
    Удаление определённой фразы
    -----------------------------------------------------------------
    */ 
    if (isset ($_GET['yes'])) {
      mysql_query("DELETE FROM `chat_vop` WHERE `id` = '" . $id . "'");
      mysql_query("OPTIMIZE TABLE `chat_vop`");
      $id_b = $res['id_bot'];
      header("location: ?act=mod_phrases&id=$id_b&do=f_u&start=$start");
     exit;
    } else {
      echo '<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id_b.'"><b>' . $lng_chat['phrases'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['deleting_the_phrase'].'</div>';
      echo '<div class="rmenu">'.$lng_chat['delete_the_phrase'].'<p><a href="?act=mod_phrases&amp;id='.$id.'&amp;mod=dell&amp;start=' . $start . '&amp;yes">'.$lng_chat['action_yes'].'</a> | <a href="?act=mod_phrases&amp;id='.$id_b.'&amp;start=' . $start . '">'.$lng_chat['action_no'].'</a></p></div>';
    }
 break;

  case 'nev':
    /*
    -----------------------------------------------------------------
    Добавление новой фразы
    -----------------------------------------------------------------
    */ 
    echo '<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id.'"><b>' . $lng_chat['phrases'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['new_phrase'].'</div>';
    if (isset ($_GET['nev_yes'])) {
    $vopros = trim($_POST['vopros'],0);    
    $otvet = isset($bot_d['tip']) ? trim($_POST['otvet']) : 0;
    $error = '';
    if (empty($vopros) || empty($otvet) && $bot_d['tip'])
      $error = $lng['error_empty_fields'] .'<br />';
    if (mysql_num_rows(mysql_query("SELECT * FROM `chat_vop` WHERE `vopros` = '" . $vopros . "' AND `id_bot` = '" . $id . "'")))
      $error = $error . $lng_chat['phrase_is_in_the_database'] .'<br />';
    if ($error) {
      echo '<div class="rmenu"><p><b>'.$lng['error'].'</b><br />' . $error . '</p></div>';
    } else {
      $result = mysql_query("INSERT INTO `chat_vop` SET `vopros` = '" . mysql_real_escape_string($vopros) . "', `otvet` = '" . mysql_real_escape_string($otvet) . "', `id_bot`='" . $id . "'");
      if ($result) {
        header("location: ?act=mod_phrases&id=$id&do=f_d");
       exit;
      } else {
        header("location: ?act=mod_phrases&id=$id&do=f_ne_d");
       exit;
      }
    }
  } else {
    echo '<div class="gmenu"><b>'.$lng_chat['new_phrase'].':</b></div>';
    echo '<form name="form" action="?act=mod_phrases&amp;mod=nev&amp;id='.$id.'&amp;start=' . $start . '&amp;nev_yes" method="POST">';
    echo '<div class="menu"><h3>'.$lng_chat['phrase'].($bot_d['tip'] == 4 ? '*' : '').'</h3>';   
    echo '<textarea rows="' . $set_user['field_h'] . '" name="vopros"></textarea></div>';
    if ($bot_d['tip']) {
      echo '<div class="menu"><h3>'.$lng_chat['reply'].($bot_d['tip'] == 4 ? '*' : '').'</h3>';
      echo '<textarea rows="' . $set_user['field_h'] . '" name="otvet"></textarea></div>';
    }
    if ($bot_d['tip'] == 4)
      echo '<div class="menu">*<small>&#160;&#160;'.$lng_chat['faq_f_mass'].'</small></div>';
    echo '<div class="gmenu"><input type="submit" name="" value="'.$lng['save'].'" />';
    echo '</div></form>';
  }
 break;

  default :
    /*
    -----------------------------------------------------------------
    Список фраз бота
    -----------------------------------------------------------------
    */ 
    $req = mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $id . "'");
    $total = mysql_result($req, 0);
    echo '<div class="phdr"><a href="?act=mod_bots"><b>' . $lng_chat['bots'] . '</b></a> | <b>'.$bot_d['name'].'</b>: '.$lng_chat['phrases'].'</div>';
    echo '<div class="topmenu"><a href="?act=mod_search&amp;id='.$id.'">'.$lng['search'].'</a> | <a href="?act=mod_phrases&amp;mod=nev&amp;id='.$id.'&amp;start=' . $start . '">'.$lng['add'].'</a></div>';

    switch ($do) {

      case 'f_i':
        echo '<div class="gmenu"><b>'.$lng_chat['sentence_amended'].'</b></div>';
     break;
    
      case 'f_ne_i':
        echo '<div class="rmenu"><b>'.$lng['error'].'</b></div>';
     break;
    
      case 's_o':
        echo '<div class="gmenu">'.$lng_chat['list_of_phrases_cleared'].'</div>';
     break;
    
      case 'o_f_u':
        echo '<div class="gmenu"><b>'.$lng_chat['marked_phrases_removed'].'</b></div>';
     break;
    
      case 'f_u':
         echo '<div class="gmenu"><b>'.$lng_chat['phrase_removed'].'</b></div>';
     break; 
      
      
      case 'f_d':
        echo '<div class="gmenu"><b>'.$lng_chat['the_phrase_is_added'].'</b></div>'; 
     break;
      
      case 'f_ne_d':
        echo '<div class="rmenu"><b>'.$lng['error'].'</b></div>'; 
     break;
      
      default :
        echo '';
    }
    
    if ($total) {
      $vopros = mysql_query("SELECT * FROM `chat_vop` WHERE `id_bot` = '" . $id . "' LIMIT $start,$kmess");
      echo '<form action="?act=mod_phrases&amp;mod=massdel&amp;id='.$id.'" method="post">';
      while ($mass = mysql_fetch_array($vopros)) {
        echo is_integer($i / 2) ? '<div class="list1">' : '<div class="list2">';
        // Если текст длинный, то обрезаем всё что более 300 символов
        if (mb_strlen($mass['vopros']) > 300) {
          $text_v = mb_substr($mass['vopros'], 0, 300);
          $text_v = functions::checkout($text_v, 1, 1);
          $text_v = preg_replace('#\[c\](.*?)\[/c\]#si', '<div class="quote">\1</div>', $text_v);
          if ($set_user['smileys'])
            $text_v = functions::smileys($text_v, 1);
          echo '<b>'.$lng_chat['phrase'].':</b> '.bbcode::notags($text_v) . '...<br />';
        } else {
          // Или, обрабатываем тэги и выводим весь текст
          $text_v = functions::checkout($mass['vopros'], 1, 1);
          if ($set_user['smileys'])
            $text_v = functions::smileys($text_v, 1);
          echo '<b>'.$lng_chat['phrase'].':</b> '.$text_v;
        } 
        if ($bot_d['tip']) {
          // Если текст длинный, то обрезаем всё что более 300 символов
          if (mb_strlen($mass['otvet']) > 300) {
            $text_o = mb_substr($mass['otvet'], 0, 300);
            $text_o = functions::checkout($text_o, 1, 1);
            $text_o = preg_replace('#\[c\](.*?)\[/c\]#si', '<div class="quote">\1</div>', $text_o);
            if ($set_user['smileys'])
              $text_o = functions::smileys($text_o, 1);
            echo '<br /><b>'.$lng_chat['reply'].':</b> '.bbcode::notags($text_o) . '...<br />';
          } else {
            // Или, обрабатываем тэги и выводим весь текст
            $text_o = functions::checkout($mass['otvet'], 1, 1);
            if ($set_user['smileys'])
              $text_o = functions::smileys($text_o, 1);
            echo '<br /><b>'.$lng_chat['reply'].':</b> '.$text_o;
          } 
        }
        echo '<div class="sub">';
        echo '<input type="checkbox" name="delch[]" value="' . $mass['id'] . '"/>&#160;';
        echo '<a href="?act=mod_phrases&amp;mod=red&amp;id=' . $mass['id'] . '&amp;start=' . $start . '">'.$lng_chat['edit'].'</a> - ';
        echo '<a href="?act=mod_phrases&amp;mod=dell&amp;id=' . $mass['id'] . '&amp;start=' . $start . '">'.$lng['delete'].'</a>';
        echo '</div>';
        echo '</div>';
       ++$i;
      }
      echo '<div class="rmenu"><input type="submit" value=" '.$lng['delete'].' "/></div>';
      echo '</form>';
      echo'<div class="phdr"><a href="menu.php">'.$lng_chat['menu'].'</a></div>';
      // Постраничная навигация
      if ($total > $kmess) {
        echo '<div class="topmenu">' . functions::display_pagination('?act=mod_phrases&amp;id='.$id.'&amp;', $start, $total, $kmess) . '</div>';
        echo '<p><form action="?act=mod_phrases&amp;id='.$id.'" method="post">';
        echo '<input type="text" name="page" size="2"/>';
        echo '<input type="submit" value="' . $lng['to_page'] . ' &gt;&gt;"/></form></p>';
      }
      echo '<p><a href="?act=mod_search&amp;id='.$id.'">'.$lng_chat['search_phrases'].'</a>';
      echo '<br /><a href="?act=mod_phrases&amp;mod=nev&amp;id='.$id.'&amp;start=' . $start . '">'.$lng_chat['add_the_phrase'].'</a>';
      echo'<br /><a href="?act=mod_phrases&amp;mod=delete&amp;id='.$id.'">'.$lng_chat['clear_list_of_phrases'].'</a></p>';
    } else {
      echo '<div class="rmenu"><p>'.$lng_chat['the_list_is_empty'].'</p></div>';
      echo '<div class="gmenu"><form action="?act=mod_phrases&amp;mod=nev&amp;id='.$id.'&amp;start=' . $start . '" method="post"><input type="submit" value="'.$lng_chat['add_the_phrase'].'" /></form></div>';
      echo'<div class="phdr"><a href="menu.php">'.$lng_chat['menu'].'</a></div>';
    }
}
if ($mod) {
  echo'<div class="phdr"><a href="?act=mod_phrases&amp;id='.$id_b.'">' . $lng['back'] . '</a></div>';
}
echo '<p><a href="../' . $set['admp'] . '/index.php">' . $lng['admin_panel'] . '</a></p>';

?>