<?php

/**
 * Mod Shoutbox Johncms 7.1.0
 * By Aan Gabriel
 *
*/

define('_IN_JOHNCMS', 1);

$headmod = 'guestbook';
require('../system/bootstrap.php');

/** @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(Johncms\Api\ConfigInterface::class);
$userConfig = $systemUser->getConfig();


/** @var Zend\I18n\Translator\Translator $translator */
$translator = $container->get(Zend\I18n\Translator\Translator::class);
$translator->addTranslationFilePattern('gettext', __DIR__ . '/locale', '/%s/default.mo');

function gio($gio){
    $time=time();
    $jun=round(($time-$gio)/60);

   if($jun<1){
        $jun='Has just finished';
    }
    if($jun>=1 && $jun<60){
        $jun="$jun Minutes ago";
    }
    if($jun>=60 && $jun<1440){
        $jun=round($jun/60); $jun="$jun hour ago";
    }
    if($jun>=1440){
       $jun=round($jun/60/24); $jun="$jun before";
    }
    return $jun;
}

if (isset($_POST['msg'])) {
     $admset = isset($_SESSION['ga']) ? 1 : 0;
     $name = isset($_POST['name']) ? mb_substr(trim($_POST['name']), 0, 20) : '';
     $msg = isset($_POST['msg']) ? mb_substr(trim($_POST['msg']), 0, 5000) : '';
    $trans = isset($_POST['msgtrans']) ? 1 : 0;
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';
    $from = $systemUser->isValid() ? $systemUser->name : 'Guest';
    if ($systemUser->isValid()) {
       $msg = str_replace('[you]', $systemUser->name, $msg);
    } else {
       $msg = str_replace('[you]', 'Guest', $msg);
    } 
    $error = [];
    $flood = false;
    if (!isset($_POST['token']) || !isset($_SESSION['token']) || $_POST['token'] != $_SESSION['token']) {
            $error[] = _t('Wrong data');
    }
    if (!$systemUser->isValid() && empty($name)) {
            $error[] = _t('You have not entered a name');
     }

    if (empty($msg)) {
            $error[] = _t('You have not entered the message');
    }

   if ($systemUser->ban['1'] || $systemUser->ban['13']) {
            $error[] = _t('Access forbidden');
   }

   // CAPTCHA для гостей
   if (!$systemUser->isValid() && (empty($code) || mb_strlen($code) < 4 || $code != $_SESSION['code'])) {
            $error[] = _t('The security code is not correct');
    }
    unset($_SESSION['code']);
    if ($systemUser->isValid()) {
            // Антифлуд для зарегистрированных пользователей
            $flood = $tools->antiflood();
     } else {
            // Антифлуд для гостей
           $req = $db->query("SELECT `time` FROM `guest` WHERE `ip` = '" . $env->getIp() . "' AND `browser` = " . $db->quote($env->getUserAgent()) . " AND `time` > '" . (time() - 60) . "'");
            

            if ($req->rowCount()) {
                $res = $req->fetch();
                $flood = time() - $res['time'];
            }
     }

     if ($flood) {
            $error = sprintf(_t('You cannot add the message so often. Please, wait %d seconds.'), $flood);
     }


      if (!$error) {
            // Проверка на одинаковые сообщения
            $req = $db->query("SELECT * FROM `guest` WHERE `user_id` = '" . $systemUser->id . "' ORDER BY `time` DESC");
            $res = $req->fetch();

            if ($res['text'] == $msg) {
                header("location: index.php");
                exit;
            }
        }
 
      if (!$error) {
            // Вставляем сообщение в базу
            $db->prepare("INSERT INTO `guest` SET
                `adm` = ?,
                `time` = ?,
                `user_id` = ?,
                `name` = ?,
                `text` = ?,
                `ip` = ?,
                `browser` = ?,
                `otvet` = ''
            ")->execute([
                $admset,
                time(),
                $systemUser->id,
                $from,
                $msg,
                $env->getIp(),
                $env->getUserAgent(),
            ]);
           include 'bot.php';


        if ($systemUser->isValid()) {
                $postguest = $systemUser->postguest + 1;
                $db->exec("UPDATE `users` SET `postguest` = '$postguest', `lastpost` = '" . time() . "' WHERE `id` = " . $systemUser->id);
         }
         header('location: index.php');
    } else {
            echo $tools->displayError($error, '<a href="index.php">' . _t('Back') . '</a>');
   }


}
if ($userConfig->chatTotal) {
    $chatTotal = $userConfig->chatTotal;
} else {
    $chatTotal = '4';
}
$total = $db->query("SELECT COUNT(*) FROM `guest` WHERE `adm`='0'")->fetchColumn();
if ($total) {
     $req = $db->query("SELECT `guest`.*, `guest`.`id` AS `gid`, `users`.`rights`, `users`.`lastdate`, `users`.`sex`, `users`.`status`, `users`.`datereg`, `users`.`id`
                FROM `guest` LEFT JOIN `users` ON `guest`.`user_id` = `users`.`id`
                WHERE `guest`.`adm`='0' ORDER BY `time` DESC LIMIT " . $chatTotal);

          for ($i = 0; $gres = $req->fetch(); ++$i) {
               $time = time();
               $jun  = round(($time - $gres['time']) / 60);
                if ($jun < 1)
                    $jun = 'topmenu';
                else
                    $jun = 'list1';
                $post = $gres['text'];
                if (strlen($post) > 160) {
                   $post = substr($post, 0, 160) . '...';
                }
               $post = $tools->checkout($gres['text'], 1, 1);
               $post = $tools->smilies($post, $gres['rights'] >= 1 ? 1 : 0);
              
               $outputhtml .= (time() > $gres['lastdate'] + 300 ? ' <div class="' . $jun . '"><font color="red">•</font> ' : ' <div class="' . $jun . '"><font color="green">•</font> ') . '<a href="javascript:tag(\'@'.$gres['name'].'\',\' \')">' . $tools->nick($gres['id']) . '</a>: ' . $post . '<br /><span style="font-size:11px;color:#777;">' . gio($gres['time']) . '</span></div>';
            
    }
    echo $outputhtml;
    if ($total > $chatTotal) {
               echo '<div class="gmenu"><a href="../guestbook/index.php"><p align="center">Read all</p></a></div>';
               }
} else {
    echo '<div class="menu"><p>' . _t('The guestbook is empty.<br><strong>Be the first! :)</strong>') . '</p></div>';
}


?>