<?php

namespace Moderation;

use Chat;
use ChatMessage;
use Core\Db;
use DateTime;
use User;

class ModFactory
{
    private const ERROR_WRONG_DURATION = 'Неверно указан срок наказания';
    public readonly string $status;
    private DateTime $time;
    private ChatMessage $msg;
    private Moderation $moderation;
    private Chat $chat;
    private array $targetUser;

    public function __construct(
        private readonly string $targetLogin,
        private readonly string $reason,
        int                     $moderatorsRoom // Комната где сидит модератор.
    )
    {
        $this->targetUser = User::getInfo($this->targetLogin);
        if (empty($this->targetUser)) {
            $this->status = 'Персонаж не найден!';
            return;
        }
        $this->chat = new Chat();
        $this->msg = new ChatMessage();
        $this->msg->setType(6);
        $this->msg->setTypeTime(1);
        $this->msg->setRoom($moderatorsRoom);
        $this->time = new DateTime();
        $this->moderation = new Moderation($this->targetUser['id']);
    }

    public function silence(int $minutes): void
    {
        if ($minutes < 1) {
            $this->status = self::ERROR_WRONG_DURATION;
            return;
        }
        $this->time->modify("+ $minutes minute");
        $this->moderation->silence($this->time, $this->reason);
        $this->status = "Персонажу $this->targetLogin запрещено общаться в чате до {$this->time->format(Moderation::EXPIRATION_DATETIME_FORMAT)}.";
        $this->msg->setText("[img[items/silence.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function unsilence(): void
    {
        if ($this->targetUser['molch1'] < $this->time->getTimestamp()) {
            $this->status = 'Персонаж не молчит!';
            return;
        }
        $this->moderation->unsilence();
        $this->status = "С персонажа $this->targetLogin снят запрет на общение в чате.";
        $this->msg->setText("[img[items/pal_button3.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function prison(int $days): void
    {
        if ($days < 1) {
            $this->status = self::ERROR_WRONG_DURATION;
            return;
        }
        $this->time->modify("+ $days day");
        $this->moderation->prison($this->time, $this->reason);
        Db::sql('delete from dungeon_zv where uid = ?', [$this->targetUser['id']]); // Удаляем заявки в пещеры.
        $this->status = "Персонаж $this->targetLogin был отправлен в тюрьму до {$this->time->format(Moderation::EXPIRATION_DATETIME_FORMAT)}.";
        $this->msg->setText("[img[items/jail.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function unprison(): void
    {
        $this->moderation->unprison();
        $this->status = "Персонаж $this->targetLogin был выпущен из тюрьмы.";
        $this->msg->setText("[img[items/jail_off.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function depersonalize(int $days): void
    {
        if ($days < 1) {
            $this->status = self::ERROR_WRONG_DURATION;
            return;
        }
        if ($this->targetUser['info_delete'] === 1 || $this->targetUser['info_delete'] >= $this->time->getTimestamp()) {
            $this->status = 'Персонаж уже под подозрением.';
            return;
        }
        $this->time->modify("+ $days day");
        $this->moderation->depersonalize($this->time, $this->reason);
        $this->status = "Персонаж $this->targetLogin под подозрением до {$this->time->format(Moderation::EXPIRATION_DATETIME_FORMAT)}";
        $this->msg->setText("[img[items/cui.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function undepersonalize(): void
    {
        if ($this->targetUser['info_delete'] <= $this->time->getTimestamp()) {
            $this->status = 'Персонаж не под подозрением.';
            return;
        }
        $this->moderation->undepersonalize();
        $this->status = "Персонаж $this->targetLogin больше не под подозрением";
        $this->msg->setText("[img[items/uncui.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function ban(): void
    {
        $this->moderation->ban($this->reason);
        Db::sql('delete from chat where login = ?', [$this->targetLogin]);
        Db::sql('insert into ban_email (email, uid, nick_name) values (?,?,?)', [$this->targetUser['mail'], $this->targetUser['id'], $this->targetLogin]);
        Db::sql('delete from zayvki where creator = ?', [$this->targetUser['id']]); // Удаляем заявки на бой.
        Db::sql('delete from dungeon_zv where uid = ?', [$this->targetUser['id']]); // Удаляем заявки в пещеры.
        if (!empty($this->targetUser['battle'])) {
            Db::sql(
                'update users left join stats on users.id = stats.id set battle = default, regHP = unix_timestamp(), team = 0, battle_yron = 0, battle_exp = 0 where users.id = ?',
                [$this->targetUser['id']]
            );
        }
        $this->status = "Персонаж $this->targetLogin заблокирован";
        $this->msg->setText("[img[items/pal_button6.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }

    public function unban(): void
    {
        if (empty($this->targetUser['banned'])) {
            $this->status = 'Персонаж не в блоке.';
            return;
        }
        $this->moderation->unban();
        Db::sql('delete from ban_email where email = ?', [$this->targetUser['mail']]);
        $this->status = "Персонаж $this->targetLogin разблокирован";
        $this->msg->setText("[img[items/pal_button7.gif]] $this->status");
        $this->chat->sendMsg($this->msg);
    }
}