<?php

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

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

/*
-----------------------------------------------------------------
Запуск ботов
-----------------------------------------------------------------
*/
$bot_mass = unserialize($k_d['bot']);
foreach ($bot_mass as $val) {
  $bot_id = intval($val);  
  $bot = mysql_query("SELECT `name`, `tip`, `mass_bot` FROM `chat_bot` WHERE `id` = '" . $bot_id . "' LIMIT 1"); // Получение данных.
  $bot_d = mysql_fetch_assoc($bot);
  $mass_bot = unserialize($bot_d['mass_bot']);
  if (mysql_num_rows($bot) || !empty($mass_bot)) {
    $soob_d = mysql_fetch_assoc(mysql_query("SELECT `id_bot`, `time`, `tip` FROM `chat_room_" . $id . "` WHERE `id_u` = '" . $bot_id . "' AND `tip` > '2' ORDER BY `time` DESC LIMIT 1")); // Получение данных
    $tim = $soob_d['time'] - 2;
    $tip = '';
    /*
    -----------------------------------------------------------------
    Переключаем режим работы бота в зависимости от его типа 
    -----------------------------------------------------------------
    */
    switch ($bot_d['tip']) {

      case 1:
        /*
        -----------------------------------------------------------------
        Вопрос
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < time() - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 6;
              $vopros = $mass_bot['vopros'];
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
          break;

          case 6:
            // никто не ответил
            if ($tim < time() - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
           }
          break;

         default:
           // новый вопрос через...
           $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
           $num = rand(1, $v1) - 1;
           $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
           $tip = 3;
           $id_bot = $vop_d['id'];
           $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 2:
        /*
        -----------------------------------------------------------------
        Вопрос с подсказкой
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < time() - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 4;
              $vopros = $mass_bot['vopros'];
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
           break;

          case 4:
            // Подсказка
            if ($tim < time() - $mass_bot['time_1'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 6;
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 4);
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_1'], array(
                '[text]' => $c
              ));
            }
           break;

          case 6:
            // никто не ответил
            if ($tim < time() - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
           }
          break;

         default:
           // новый вопрос через...
           $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
           $num = rand(1, $v1) - 1; // Случайный вопрос
           $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
           $tip = 3;
           $id_bot = $vop_d['id'];
           $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 3:
        /*
        -----------------------------------------------------------------
        Вопрос с 2 подсказками
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Вопрос
            if ($tim < time() - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 4;
              $vopros = $mass_bot['vopros'];
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vik['vopros'],
                '[text_count]' => mb_strlen($vik['otvet'])
              ));
            }
           break;
   
          case 4:
            // Подсказка
            if ($tim < time() - $mass_bot['time_1'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 5;
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 4);
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_1'], array(
                '[text]' => $c
              ));
            }
           break;
 
          case 5:
            // Вторая подсказка
            if ($tim < time() - $mass_bot['time_2'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $ans = $vik['otvet'];
              $b = mb_strlen($ans);
              $d = round($b / 3) + 1;
              $c = mb_substr($ans, 0, $d);
              for ($z = $d; $z < $b; ++$z) {
                $c = "$c*";
              }
              $tip = 6;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['pods_2'], array(
                '[text]' => $c
              ));
            }
           break;

          case 6:
            // никто не ответил
            if ($tim < time() - $mass_bot['time_on'] - $mass_bot['time_off']) {
              $vik = mysql_fetch_assoc(mysql_query("SELECT `otvet` FROM `chat_vop` WHERE `id` = '" . $soob_d['id_bot'] . "' LIMIT 1"));
              $tip = 7;
              $id_bot = $soob_d['id_bot'];
              $text = strtr($mass_bot['no_otv'], array(
                '[text]' => $vik['otvet']
              ));
            }
          break;

         default:
           // новый вопрос через...
           $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
           $num = rand(1, $v1) - 1; // Случайный вопрос
           $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
           $tip = 3;
           $id_bot = $vop_d['id'];
           $text = strtr($mass_bot['nev_vop'], array(
              '[time]' => $mass_bot['time_off']
            ));
        }
     break;

      case 4:
        /*
        -----------------------------------------------------------------
        Диалог
        -----------------------------------------------------------------
        */
        $soob2 = mysql_query("SELECT `id_bot`, `time`, `text`, `tip` FROM `chat_room_" . $id . "` WHERE `id_u`='" . $user_id . "' OR `id_bot`='" . $user_id . "' AND `id_u`='" . $bot_id . "' ORDER BY `time` DESC LIMIT 1");
        if (mysql_num_rows($soob2)) {
          $soob_d2 = mysql_fetch_assoc($soob2);
          if (!$soob_d2['id_bot']) {
            $ttt = $soob_d2['time'] + $mass_bot['time_off'];
            if ($ttt < time()) {
              $text2 = $soob_d2['text'];
              $text2 = preg_replace('#\[c\](.*?)\[/c\]#si', '', $text2);
              $text2 = strtr($text2, array (
                '.' => '',
                ',' => '',
                '?' => ' ?',
                '!' => ' !',
                ':' => ' :',
                ')' => ' )',
                '(' => ' (',
                'www' => ' www ',
                '"' => '',
                '*' => '',
                '/' => ''
              ));
              $top = 0;
              $b2 = explode(' ', $text2);
              $col = count($b2);
              for ($i2 = 0; $i2 < $col; ++$i2) {
                $umnik2 = mysql_query("SELECT `id` FROM `chat_vop` WHERE `id_bot`='" . $bot_id . "' AND `vopros` like '%" . $b2[$i2] . "%'");
                if (mysql_num_rows($umnik2)) {
                  while($umnik2_post = mysql_fetch_assoc($umnik2)) {
                    $sov = 0;
                    $vop = mysql_query("SELECT `vopros`, `otvet` FROM `chat_vop` WHERE `id` = '" . $umnik2_post['id'] . "' LIMIT 1");
                    $vop_d = mysql_fetch_assoc($vop);
                    $mass = $vop_d['vopros'];
                    $vs = explode(' ', $mass);
                    $i3 = 0;
                    while($i3 < $col) {
                      if (in_array($b2[$i3], $vs)) {
                        ++$sov;
                      }
                     ++$i3;
                    }
                    if ($top <= $sov) {
                      $top = $sov;
                      $otvet = $vop_d['otvet'];
                      if (count($vs) == $sov) {
                        ++$top;
                      }
                    }
                  }
                }
              }
              if ($top) {
                // Ответ из базы
                $otvet = explode("|", $otvet);
                $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
                $otvet = strtr($mass_bot['vopros'], array(
                  '[text]' => $otvet
                ));
                $tip = 8;
              } else {
                // неизвестная фраза
                $otvet = explode("|", $mass_bot['no_otv']); 
                $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
                $tip = 8;
              }
            }
          } elseif ($soob_d2['id_bot'] == $user_id && $soob_d2['tip'] != 9) {
            if (($soob_d2['time'] + $mass_bot['time_1']) < time()) {
              // вышло время ожидания на вопрос  
              $otvet = explode("I", $mass_bot['nev_vop']);
              $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
              $tip = 9;
            }
          }  
        } else {
          // поговорим? 
          $otvet = explode("I", $mass_bot['vopros']);
          $otvet = $otvet[mt_rand(0, (count($otvet) - 1))];
          $tip = 8;
        }
        if ($tip) {
          $id_bot = $user_id;  
          $text = strtr($otvet, array(
            '[login]' => $login
          ));
        }
     break;



      default:
         /*
        -----------------------------------------------------------------
        Фраза
        -----------------------------------------------------------------
        */
        switch ($soob_d['tip']) {

          case 3:
            // Фраза
            if ($tim < time() - $mass_bot['time_off']) {
              $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
              $num = rand(1, $v1) - 1;
              $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id`, `vopros` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
              $tip = 3;
              $id_bot = $vop_d['id'];
              $text = strtr($mass_bot['vopros'], array(
                '[text]' => $vop_d['vopros']
              ));
            }
           break;

         default:
           // Новая фраза
           $v1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "'"), 0);
           $num = rand(1, $v1) - 1;
           $vop_d = mysql_fetch_assoc(mysql_query("SELECT `id`, `vopros` FROM `chat_vop` WHERE `id_bot` = '" . $bot_id . "' LIMIT " . $num . ",1"));
           $tip = 3;
           $id_bot = $vop_d['id'];
           $text = strtr($mass_bot['vopros'], array(
              '[text]' => $vop_d['vopros']
            ));
        }
    }
    // Заносим сообщение в б.д.
    if ($tip) {
      $mass_bot_post = serialize(array (
        'av' => $mass_bot['av'],
        'sex' => $mass_bot['sex'],
        'status' => $mass_bot['status'],
        'name' => $bot_d['name'],
        'name_delete' => '',
        'cvet' => '',
        'cvet_n' => '',
        'ip' => '2130706433',
        'soft' => 'k_2_bot',
        'rights' => 0
        ));
      mysql_query("INSERT INTO `chat_room_" . $id . "` SET
        `id_u` = '" . $bot_id . "',
        `id_bot` = '" . $id_bot . "',
        `time` = '" . (time()+2) . "',
        `text` = '" . mysql_real_escape_string($text) . "',
        `author` = '" . mysql_real_escape_string($mass_bot_post) . "',
        `tip` = '" . $tip . "'
      ");
    }
  }
}
?>