<?php
# Date: 23.08.2021 (23:05)
namespace Battles;

use Battles\Database\Db;

class Clan
{
    private static ?self $_instance = null;
    private $clan;

    private function __construct()
    {
        $this->clan = Db::getInstance()->ofetch('select * from clans where owner_id = ?', User::getInstance()->getId());
    }

    public static function getInstance(): self
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function addMember(string $login): string
    {
        $error = null;
        if (!$this->getProverka(User::getInstance($login)->getId())) {
            $error .= '<br>Нет проверки!';
        }
        if (User::getInstance($login)->getClan()) {
            $error .= '<br>Персонаж уже состоит в клане!';
        }
        if (User::getInstance($login)->getLevel() < 1) {
            $error .= '<br>Персонаж 0 уровня не может быть принят!';
        }
        if (User::getInstance()->getMoney() < GameConfigs::CLAN['add_member_cost']) {
            $error .= '<br>Недостаточно денег!';
        }
        if ($error) {
            return $error;
        }
        User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['add_member_cost']);
        User::getInstance()->saveMoney();
        User::getInstance($login)->setClan(User::getInstance()->getClan());
        return "Персонаж «{$login}» успешно принят в клан.";
    }

    public function removeMember(string $login): string
    {
        $error = null;
        if (User::getInstance()->getMoney() < GameConfigs::CLAN['remove_member_cost']) {
            $error .= '<br>Недостаточно денег!';
        }
        if (User::getInstance($login)->getId() === User::getInstance()->getId()) {
            $error .= '<br>Себя выгонять нельзя!';
        }
        if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) {
            $error .= '<br>Персонаж не состоит в этом клане!';
        }
        if ($error) {
            return $error;
        }
        User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['remove_member_cost']);
        User::getInstance()->saveMoney();
        User::getInstance($login)->setClan(null);
        return "Персонаж «{$login}» покинул клан.";
    }

    public function changeOwner(string $login): string
    {
        $error = null;
        if (User::getInstance($login)->getId() === User::getInstance()->getId()) {
            $error .= '<br>Самоудовлетворяетесь? ;)';
        }
        if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) {
            $error .= '<br>Персонаж не состоит в этом клане!';
        }
        if ($error) {
            return $error;
        }
        Db::getInstance()->execute('update clans set owner_id = ? where owner_id = ?', [User::getInstance($login)->getId(), User::getInstance()->getId()]);
        return 'Вы передали управление кланом персонажу «' . $login . '».';
    }

    public function setClanInfo(string $text): string
    {
        $checkId = Db::getInstance()->fetchColumn('select id from users where clan = (select short_name from clans where owner_id = ?)', User::getInstance()->getId());
        if ($checkId !== User::getInstance()->getId()) {
            return 'Ошибка доступа!';
        }
        Db::getInstance()->execute('update clans set info = ? where owner_id = ?', [$text, $checkId]);
        return 'Описание клана изменено!';
    }

    public function getMemberlist(): array
    {
        return Db::getInstance()->fetchAll('select id, (select 1 from clans where short_name = clan and owner_id = id) as clan_owner, room from users where clan = ? order by clan_owner desc, room, login', User::getInstance()->getClan());
    }

    private function getProverka($user_id)
    {
        return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = 20 and owner_id = ?', $user_id);
    }

    public function getClanOwnerId(): ?int
    {
        return $this->clan->owner_id;
    }

    public function getClanName(): ?string
    {
        return $this->clan->full_name;
    }

    public function getClanShortName(): ?string
    {
        return $this->clan->short_name;
    }
}