<?php

namespace Battles;

use Battles\Database\Db;
use DateTime;
use Exception;

class Chat
{
    private DateTime $d;
    private Db $db;

    public function __construct(Db $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::getInstance()->getId(), User::getInstance()->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' && empty($row->rid)) {
                $wrappedMessage .= sprintf('<span class="chatsys">%s %s</span><br>', $this->d->format('H:i'), $m);
            } elseif ($row->rid === User::getInstance()->getId()) {
                if ($row->type === 'sys') {
                    $wrappedMessage .= sprintf('<span class="chatsys">%s [Система] → %s</span><br>', $this->d->format('H:i'), $m);
                } elseif ($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 sendMessage(string $msg)
    {
        $this->db->execute('insert into chat (user_id, msg) values (?,?)', [User::getInstance()->getId(), $msg]);
    }

    public static function sendSys(string $msg, ?int $receiver_id = null)
    {
        Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiver_id, 'sys']);
    }
    public static function sendTelegraf(string $msg, int $receiver_id)
    {
        Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiver_id, 'sms']);
    }

}