<?php

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

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\EnvironmentInterface $env */
$env = $container->get(Johncms\Api\EnvironmentInterface::class);

/** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

/** @var Johncms\Api\ConfigInterface $config */

$config = $container->get('config')['johncms']; 

if ($systemUser->rights < 9) {
    header('Location: ../?err');
    exit;
}

$from = isset($_GET['from']) ? trim($_GET['from']) : '';
$id = isset($_GET['id']) ? abs(intval($_GET['id'])) : 0;

$headmod = 'botpanel';
$textl = 'BOT Panel';

switch ($from) {
      case 'add':
         if (isset($_POST['submit'])) {
            $key = filter_has_var(INPUT_POST, 'key')
    ? mb_substr(filter_var($_POST['key'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $text = filter_has_var(INPUT_POST, 'text')
    ? mb_substr(filter_var($_POST['text'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $txt1 = filter_has_var(INPUT_POST, 'txt1')
    ? mb_substr(filter_var($_POST['txt1'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $txt2 = filter_has_var(INPUT_POST, 'txt2')
    ? mb_substr(filter_var($_POST['txt2'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
           $txt3 = filter_has_var(INPUT_POST, 'txt3')
    ? mb_substr(filter_var($_POST['txt3'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';

              //$key = isset($_POST['key']) ? trim($_POST['key']) : '';
            //$key = htmlentities($_POST['key'], ENT_QUOTES, 'UTF-8');
            //$text = isset($_POST['text']) ? trim($_POST['text']) : '';
            //$txt1 = isset($_POST['txt1']) ? trim($_POST['txt1']) : '';
            //$txt2 = isset($_POST['txt2']) ? trim($_POST['txt2']) : '';
            //$txt3 = isset($_POST['txt3']) ? trim($_POST['txt3']) : '';
            $error = [];
            $check = $db->query("SELECT COUNT(*) FROM `bot` WHERE `key`='$key'")->fetchColumn();
            if (!$key) {
               $error[] = 'Please Inserted key';
            }
            if (!$text) {
               $error[] = 'Please Inserted Text';
            }
            if ($check > 0) {
               $error[] = 'Error bot filed! Not found';
            }
           if (!$error) {
              $db->prepare('
                INSERT INTO `bot` SET
                `time` = ?,
                `user` = ?,
                `text` = ?,
                `txt1` = ?,
                `txt2` = ?,
                `txt3` = ?,
                `key` = ?
              ')->execute([        
                 time(),
                 $systemUser->name,
                 $text,
                 $txt1,
                 $txt2,
                 $txt3,
                 $key,
              ]);
             echo '<div class="gmenu">Success added<br/><a href="index.php?act=bot">Continue</a></div>';
           } else {
             echo $tools->displayError($error, '<a href="index.php?act=bot">Back</a>');
           }
         } else {
echo '<div class="mainblok">' .
           '<div class="phdr"><b>Bot Panel</b>' .
           '</div>' .
           '<div class="gmenu">' .
           '<form action="index.php?act=bot&amp;from=add" method="post">' .
           '<span class="red">*</span> Key:<br/>' .
           '<input type="text" name="key">' .
           '<br/><span class="red">*</span> Text:<br/>' .
           '<input type="text" name="text">' .
           '<br/>Text 1<br/>' .
           '<input type="text" name="txt1">' .
           '<br/>Text 2<br/>' .
           '<input type="text" name="txt2">' .
           '<br/>Text 3<br/>' .
           '<input type="text" name="txt3">' .
           '<br><input type="submit" name="submit" value="Add">' .
           '</form></div></div>';
       echo '<div class="mainblok">' .
           '<div class="phdr">' .
           '<b>Information</b></div>' .
           '<div class="topmenu">' .
           '<b>{user}</b> To nick user' .
           '<br/><b>{text}</b> Text' .
           '<br/><b>{reply}</b> Reply' .
           '</div></div>';
         }
   break;
   case 'del':
   if ($id) {
     //$id = intval($_GET['id']);
     $exist = $db->query("SELECT COUNT(*) FROM `bot` WHERE `id`='$id'")->fetchColumn();
     $uexist = $db->query("SELECT COUNT(*) FROM `bot` WHERE `id`='$id' AND `user`='$systemUser->name'")->fetchColumn();
     $error = [];
    if(!$exist) {
       $error[] = 'Error! Not found on the server';
     }
    if(!$uexist && $systemUser->rights < 9) {
      $error[] = 'You cant remove this';
    }
    if(!$error) {
       $db->exec("DELETE FROM `bot` WHERE `id`='$id'");
        echo '<div class="gmenu">Success Removed<br/><a href="index.php?act=bot">Continue</a></div>';
        } else {
             echo $tools->displayError($error, '<a href="index.php?act=bot">Back</a>');
        }
   } else {
     echo $tools->displayError('Not Found', '<a href="index.php?act=bot">Back</a>');
   }
   break;
   case 'edit':
   if ($id) {
      //$id = intval($_GET['id']);
      $echeck = $db->query("SELECT COUNT(*) FROM `bot` WHERE `key`='$key'")->fetchColumn();
      $edit = $db->query("SELECT * FROM `bot` WHERE `id`='$id' LIMIT 1")->fetch();
      $euexist = $db->query("SELECT COUNT(*) FROM `bot` WHERE `id`='$id' AND `user`='$systemUser->name'")->fetchColumn();
      $eexist = $db->query("SELECT COUNT(*) FROM `bot` WHERE `id`='$id'")->fetchColumn();
      if (isset($_POST['submit'])) {
            $key = filter_has_var(INPUT_POST, 'key')
    ? mb_substr(filter_var($_POST['key'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $text = filter_has_var(INPUT_POST, 'text')
    ? mb_substr(filter_var($_POST['text'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $txt1 = filter_has_var(INPUT_POST, 'txt1')
    ? mb_substr(filter_var($_POST['txt1'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
            $txt2 = filter_has_var(INPUT_POST, 'txt2')
    ? mb_substr(filter_var($_POST['txt2'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';
           $txt3 = filter_has_var(INPUT_POST, 'txt3')
    ? mb_substr(filter_var($_POST['txt3'], FILTER_SANITIZE_SPECIAL_CHARS, ['flag' => FILTER_FLAG_ENCODE_HIGH]), 0, 100)
    : '';



            //$key = isset($_POST['key']) ? trim($_POST['key']) : '';
            //$key = htmlentities($_POST['key'], ENT_QUOTES, 'UTF-8');
            //$text = isset($_POST['text']) ? trim($_POST['text']) : '';
            //$txt1 = isset($_POST['txt1']) ? trim($_POST['txt1']) : '';
            //$txt2 = isset($_POST['txt2']) ? trim($_POST['txt2']) : '';
            //$txt3 = isset($_POST['txt3']) ? trim($_POST['txt3']) : '';
            $error = [];
            if (!$euexist && $systemUser->rights < 9) {
               $error[] = 'You cant edit this';
            }
           if (!$key) {
              $error[] = 'Key error not found';
           }
           if ($echeck > 0) {
              $error[] = 'Not Found';
           }
           if (!$error) {
              $db->prepare('
                 UPDATE `bot` SET
                 `time` = ?,
                 `text` = ?,
                 `txt1` = ?,
                 `txt2` = ?,
                 `txt3` = ?,
                 `key` = ?
                  WHERE `id` = ?
             ')->execute([        
                 time(),
                 $text,
                 $txt1,
                 $txt2,
                 $txt3,
                 $key,
                 $id,
              ]);
              echo '<div class="gmenu">Success Saved<br/><a href="index.php?act=bot">Continue</a></div>';
         } else {
              echo $tools->displayError($error, '<a href="index.php?act=bot">Back</a>');
         }
     } else {
       echo '<div class="mainblok">' .
           '<div class="phdr">' .
           '<b>Set BOT</b></div>' .
           '<div class="gmenu">' .
           '<form action="index.php?act=bot&amp;from=edit&amp;id='.$id.'" method="post">' .
           'Edit Key<br><input type="text" name="key" value="' . htmlentities($edit['key'], ENT_QUOTES, 'UTF-8'). '">' .
           '<br>Text key<br><input type="text" name="text" value="' . htmlentities($edit['text'], ENT_QUOTES, 'UTF-8'). '">' .
           '<br>Text 1<br><input type="text" name="txt1" value="' . htmlentities($edit['txt1'], ENT_QUOTES, 'UTF-8'). '">' .
           '<br>Text 2<br><input type="text" name="txt2" value="' . htmlentities($edit['txt2'], ENT_QUOTES, 'UTF-8'). '">' .
           '<br>Text 3<br><input type="text" name="txt3" value="' . htmlentities($edit['txt3'], ENT_QUOTES, 'UTF-8'). '">' .
           '<br><input type="submit" name="submit" value="submit"></form></div></div>';
     }
  } else {
  echo $tools->displayError('Not Found', '<a href="index.php?act=bot">Back</a>');
  }
  break;
  case 'sett':
  echo '<div class="mainblok">';
  echo '<div class="phdr"><a href="index.php"><b>' . _t('Admin Panel') . '</b></a> | ' . _t('Permissions') . '</div>';
     if (isset($_POST['submit'])) {
        $config['bot_reg'] = isset($_POST['reg']) ? intval($_POST['reg']) : 0;
        $config['bot_th'] = isset($_POST['th']) ? intval($_POST['th']) : 0;
        $config['bot_name'] = isset($_POST['name']) ? trim($_POST['name']) : 'Robot';
        $config['bot_id'] = isset($_POST['id']) ? intval($_POST['id']) : 0; 
        $configFile = "<?php\n\n" . 'return ' . var_export(['johncms' => $config], true) . ";\n";

        if (!file_put_contents(ROOT_PATH . 'system/config/system.local.php', $configFile)) {
           echo 'ERROR: Can not write system.local.php</body></html>';
           exit;
         }
        echo '<div class="rmenu">' . _t('Settings are saved successfully') . '</div>';
    }
   $color = ['red', 'green'];
   echo '<form method="post" action="index.php?act=bot&amp;from=sett">';
   echo '<div class="topmenu">' .
          'Name:<br>' . '<input type="text" name="name" value="' . htmlentities($config['bot_name'], ENT_QUOTES, 'UTF-8') . '"/><br>' .
          'ID:<br>' . '<input type="text" name="id" value="' . intval($config['bot_id']) . '"/><br>' .
        '</div>';
   echo '<div class="menu"><p>' .
    '<h3><img src="../images/' . $color[$config['bot_reg']] . '.gif" width="16" height="16" class="left"/>&#160;New Registered</h3>' .
    '<div style="font-size: x-small">' .
    '<input type="radio" value="1" name="reg" ' . ($config['bot_reg'] == 1 ? 'checked="checked"' : '') . '/>&#160;ON<br>' .
    '<input type="radio" value="0" name="reg" ' . (!$config['bot_reg'] ? 'checked="checked"' : '') . '/>&#160;OFF</div></p>'; 
    echo '<p><h3><img src="../images/' . $color[$config['bot_th']] . '.gif" width="16" height="16" class="left"/>&#160;New Topic</h3>' .
    '<div style="font-size: x-small">' .
    '<input type="radio" value="1" name="th" ' . ($config['bot_th'] == 1 ? 'checked="checked"' : '') . '/>&#160;ON<br>' .
    '<input type="radio" value="0" name="th" ' . (!$config['bot_th'] ? 'checked="checked"' : '') . '/>&#160;OFF<br>' .
    '</div></p></div>'; 
   echo '<div class="phdr"><small>Modif Bot Panel By: Aan Gabriel Elfha Gymkhana</small></div><div class="topmenu">' .
    '<p><input type="submit" name="submit" id="button" value="' . _t('Save') . '" /></p>' .
    '<p><a href="index.php">' . _t('Admin Panel') . '</a></p></div></form>'; 
  echo '</div>';
  break;
  default:
    echo '<div class="mainblok">' .
              '<div class="phdr">' .
              '<b>Bot Panel</b>' .
              '</div>' .
              '<div class="menu">'.
              '<a href="index.php?act=bot&amp;from=add">Add Answare</a></div>' .
              '<div class="menu">'.
              '<a href="index.php?act=bot&amp;from=sett">Bot Settings</a></div>' .
              '</div>';
    echo '<div class="mainblok">';
    echo '<div class="phdr">' .
              '<b>Total</b></div>';
    $total = $db->query("SELECT COUNT(*) FROM `bot`")->fetchColumn();
    if ($total > 0) {
      $req = $db->query("SELECT * FROM `bot` ORDER BY `time` DESC LIMIT $start, $kmess");
      for ($i = 0; $bot = $req->fetch(); ++$i) { 
       echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
       echo '<b>Key: </b> '.$bot['key'].'<br/>' .
                 '<b>Text: </b> '.$bot['text'];
       echo '<br/>' . ($bot['txt1'] ? '<b>Text 1:</b> '.$bot['txt1'].'<br/>' : '');
       echo ($bot['txt2'] ? '<b>Text 2:</b> '.$bot['txt2'].'<br>' : '');
       echo ($bot['txt3'] ? '<b>Text 3:</b> '.$bot['txt3'].'<br>' : '');
       echo '<b>Add:</b>'.$bot['user'].'<br><b>Time:</b>' . $tools->displayDate($bot['time']).'';
       if ($systemUser->rights >= 9) {
          echo '<br/><a href="index.php?act=bot&amp;from=edit&amp;id='.$bot['id'].'">[edit]</a> | <a href="index.php?act=bot&amp;from=del&amp;id='.$bot['id'].'">[delete]</a>';
       }
         echo '</div>';
       } 
 
       echo '<div class="phdr">Total: ' . $total . '</div>';
       echo '</div>';
        if ($total > $kmess) {
            echo '<p>' . $tools->displayPagination('index.php?act=bot&amp;', $start, $total, $kmess) . '</p>';
            echo '<p><form action="index.php?act=bot" method="get"><input type="text" name="page" size="2"/><input type="submit" value="To Page &gt;&gt;"/></form></p>';
        }
      }
  else {
      echo '<div class="rmenu">No message found!</div></div>';
     }

break;
}

?>