battles/classes/Battles/Chat.php

68 lines
2.2 KiB
PHP

<?php
namespace Battles;
use Battles\Database\DBPDO;
use DateTime;
use Exception;
class Chat
{
private DateTime $d;
private DBPDO $db;
public function __construct(DBPDO $db)
{
$this->db = $db;
}
public function getMessages(): ?string
{
$query = 'select
msg,
msgdate,
type,
s.login as sender,
r.login as receiver,
s.id as sid,
r.id as rid
from chat
left join users s on s.id = chat.user_id
left join users r on r.id = chat.receiver_id
where
r.id = ?
or r.id is null
or s.id = ?
order by chat.id';
$chatrows = $this->db->ofetchALL($query, [User::$current->getId(), User::$current->getId()]);
$wrappedMessage = null;
foreach ($chatrows as $row) {
try {
$this->d = new DateTime($row->msgdate);
} catch (Exception $e) {
echo 'Chat Datetime Whoops!';
}
$m = htmlspecialchars($row->msg);
if ($row->type === 'sys') {
$wrappedMessage .= sprintf('<span class="chatsys">%s %s</span><br>', $this->d->format('H:i'), $m);
} elseif ($row->rid == User::$current->getId()) {
if ($row->type == 'sms') {
$wrappedMessage .= sprintf('<span class="chatsms">%s Телеграмма от [%s]: %s</span><br>', $this->d->format('d.m.Y H:i'), $row->sender, $m);
} elseif ($row->type == 'private') {
$wrappedMessage .= sprintf('<span class="chatprivate">%s [%s] → [%s]: %s</span><br>', $this->d->format('H:i'), $row->sender, $row->receiver, $m);
} else {
$wrappedMessage .= sprintf('%s [%s] → [%s]: %s<br>', $this->d->format('H:i'), $row->sender, $row->receiver, $m);
}
} else {
$wrappedMessage .= sprintf('%s [%s]: %s<br>', $this->d->format('H:i'), $row->sender, $m);
}
}
return $wrappedMessage;
}
public function addMessage($msg)
{
$this->db->execute('insert into chat (user_id, msg) values (?,?)', [User::$current->getId(), $msg]);
}
}