<?php

class User
{
    public $id;
    public $login;
    public $email;
    public $realname;
    public $borndate;
    public $info;
    public $level;
    public $align;
    public $clan;
    public $money;
    public $strength;
    public $dexterity;
    public $intuition;
    public $endurance;
    public $intelligence;
    public $wisdom;
    public $ip;
    public $session_id;
    public $admin;
    public $enter_game;
    public $room;
    public $block;
    public $shadow;
    // Пока несуществующие, для совместимости.
    public $married;
    public $experience;
    public $stat_points;
    //Статусы того, кто смотрит на информацию.
    public $watcher_id;
    protected $watcherIsAdmin;
    protected $watcherIsModerator;

    use Rooms;

    public function __construct($user)
    {
        $user_query = db::c()->query('SELECT * FROM users WHERE id = "?s" OR login = "?s"', $user, $user)->fetch_assoc();
        foreach ($this as $key => $value) {
            if (isset($user_query[$key])) {
                $this->$key = $user_query[$key];
            }
        }
    }

    private function UserInfoDoll($isBattle = 0)
    {
        //https://jsfiddle.net/ngx0yvhc
        $dressed_items = db::c()->query('SELECT * FROM inventory WHERE owner_id = ?i AND dressed_slot > 0', $this->id);
        while ($row = $dressed_items->fetch_assoc()) {
            $dressed_item[$row['dressed_slot']] = $row;
        }
        for ($i = 1; $i <= 12; $i++) {
            echo sprintf('<div class="slot-%s">', $i);
            if (isset($dressed_item[$i])) {
                $itemString = '<img src="/i/sh/%s" class="item-wrap-normal tip" alt="%s"><span class="tiptext"><strong>%s</strong></span>';
                echo sprintf($itemString, $dressed_item[$i]['image'], $dressed_item[$i]['name'], $dressed_item[$i]['name']);
            } else {
                echo sprintf('<img src="/i/sh/noitem.png" class="item-wrap-normal" title="Пустой слот [%s]" alt="Пустой слот [%s]">', $i, $i);
            }
            echo sprintf('</div><!-- slot-%s -->', $i);
        }
        echo '<div class="slot-image">';
        if ($isBattle) {
            $sh = '<img src="/i/shadow/%s" alt="%s" class="tip"><span class="tiptext"><b>%s</b>Уровень: %s<br>Сила: %s<br>Ловкость: %s<br>Интуиция: %s<br>Выносливость: %s<br>Интеллект: %s<br>Мудрость: %s</span>';
            echo sprintf($sh, $this->shadow, $this->login, $this->login, $this->level, $this->strength, $this->dexterity, $this->intuition, $this->endurance, $this->intelligence, $this->wisdom);
            unset($sh);
        } else {
            echo '<img src="/i/shadow/' . $this->shadow . '" alt="' . $this->login . '">';
        }
        echo '</div><!-- slot-image -->';
    }

    private function UserInfoStats($isMainWindow = 0)
    {
        $captions = 'Уровень:<br>Сила:<br>Ловкость:<br>Интуиция:<br>Выносливость:<br>Интеллект:<br>Мудрость:<br>Местонахождение:';
        $variables = $this->level . '<br>' . $this->getStrength() . '<br>' . $this->getDexterity() . '<br>' . $this->getIntuition() . '<br>' . $this->getEndurance() . '<br>' . $this->getIntelligence() . '<br>' . $this->getWisdom() . '<br>' . $this->getRoomName($this->room);
        if ($isMainWindow) {
            $this->Bank = new Bank($this->id);
            $captions = 'Уровень:<br>Сила:<br>Ловкость:<br>Интуиция:<br>Выносливость:<br>Интеллект:<br>Мудрость:<br>Опыт:<br>Очки характеристик:<br>Деньги:<br>Деньги в банке:';
            $variables = $this->level . '<br>' . $this->getStrength(1) . '<br>' . $this->getDexterity(1) . '<br>' . $this->getIntuition(1) . '<br>' . $this->getEndurance(1) . '<br>' . $this->getIntelligence(1) . '<br>' . $this->getWisdom(1) . '<br>' . $this->experience . '<br>' . $this->stat_points . '<br>' . $this->money . '<br>' . $this->Bank->money;
        }

        if ($this->align) {
            $nameString = sprintf('<img src="/i/align_%s.png" >', $this->align);
        }
        if ($this->block) {
            $nameString .= '<span class="private"><s>' . $this->login . '</s></span>';
        } else {
            $nameString .= ' <b>' . $this->login . '</b> ';
        }
        if ($this->clan) {
            $nameString .= sprintf('<img src="/i/klan/%s.png" >', ClanImage($this->clan));
        }
        echo '<div class="user-info">';
        echo '<div class="info">';
        echo '<b>' . $nameString . '</b>';
        echo '</div><!-- info -->';
        echo '<div class="stats-container">';
        echo '<div class="column">';
        echo $captions;
        echo '</div><!-- column -->';
        echo '<div class="column">';
        echo $variables;
        echo '</div><!-- column -->';
        echo '</div><!-- stats-container -->';
        echo '<div class="debug">TODO: Сделать рассчёт здоровья и модификаторов. Вывести полоску здоровья когда будет от чего отталкиваться.</div>';
        echo '</div><!-- user-info -->';
    }

    private function getStrength($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->strength);
        }
        return $this->strength;
    }

    private function getDexterity($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->dexterity);
        }
        return $this->strength;
    }

    private function getIntuition($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->intuition);
        }
        return $this->strength;
    }

    private function getEndurance($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->endurance);
        }
        return $this->strength;
    }

    private function getIntelligence($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->intelligence);
        }
        return $this->strength;
    }

    private function getWisdom($isMainWindow = 0)
    {
        if ($this->stat_points && $isMainWindow) {
            return sprintf('%s <a href="#">[+]</a>', $this->wisdom);
        }
        return $this->strength;
    }

    private function UserInfo()
    {
        echo '<div class="user-info-container">';
        $this->UserInfoDoll();
        $this->UserInfoStats();
        echo '<div class="slot-lower">';
        if ($this->married) {
            echo sprintf('<a href = "inf.php?%s" target = _blank ><img alt = "В браке с %s" src = "i/married.gif" title = "В браке с %s"></a >', $this->married, $this->married, $this->married);
        }
        echo '</div><!-- slot-lower -->';
        echo '<div class="user-signs">';
        echo sprintf('<img src="i/zodiac/%s.png" alt="Родовой знак">', $this->showStarSign());
        echo '</div><!-- user-signs -->';
        echo '</div><!-- user-info-container -->';
        echo '<hr><!-- Нижняя часть -->';
        echo '<div class="user-info-container-lower">';
        echo '<h2>Об игроке</h2>';
        if ($this->realname) {
            echo sprintf('Имя: %s<br>', $this->realname);
        }
        if ($this->info) {
            echo nl2br($this->info);
        }
        echo '</div><!-- user-info-container-lower -->';

        if ($this->watcherIsAdmin || $this->watcherIsModerator) {
            echo '<div class="secret-info">';
            $infoString = 'E-Mail: %s<br>  ДР Игрока: %s<br> IP Регистрации: %s';
            echo sprintf($infoString, $this->email, date('d.m.Y', strtotime($this->borndate)), $this->ip);
            if ($this->watcherIsAdmin) {
                $this->Bank = new Bank($this->id);
                $infoString = '<br><span>ИД Игрока: %s<br> ИД Комнаты: %s<br> Деньги: %s<br> Деньги в банке: %s<br> Опыт: %s<br> Нераспределённые очки: %s<br> Текущая сессия: %s</span>';
                echo sprintf($infoString, $this->id, $this->room, $this->money, $this->Bank->money, $this->experience, $this->stat_points, $this->session_id);
            }
            $this->UserLogs = new UserLogModel($this->id);
            echo '<div class="secret-info-user-log"><b>Личное дело</b><br>';
            while ($userLogRow = $this->UserLogs->getUserLog()->fetch_object()) {
                echo sprintf('<code>%s</code><br>', date("d.m.Y H:i ", strtotime($userLogRow->date)) . $userLogRow->text);
            }
            echo '</div><!-- secret-info-user-log -->';
            echo '</div><!-- secret-info -->';
        }
    }

    private function WatcherStatus()
    {
        $query = db::c()->query('SELECT `align`,`admin` FROM `users` WHERE `id` = ?i', $this->watcher_id)->fetch_assoc();
        if ($query['admin']) {
            $this->watcherIsAdmin = 1;
        }
        if ($query['align'] == 1) {
            $this->watcherIsModerator = 1;
        }
    }

    public function showUserInfo()
    {
        $this->effects = new EffectsModel($this->id);
        $this->WatcherStatus();

        if ($this->block && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
            throw new Exception('<span class="error">Персонаж ' . $this->login . ' заблокирован!</span>');
        } elseif ($this->effects->getHideUserInfoStatus() && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
            if ($this->effects->getHideUserInfoStatus() == -1) {
                $date = 'навсегда';
            } else {
                $date = 'до' . date('d.m.Y', strtotime($this->effects->getHideUserInfoStatus()));
            }
            throw new Exception('<span class="error">Персонаж ' . $this->login . ' обезличен ' . $date . '.</span>');
        } else {
            $this->UserInfo();
        }
    }

    public function showUserDoll($isBattle = 0)
    {
        echo '<div class="user-info-container">';
        $this->UserInfoDoll($isBattle);
        echo '</div><!-- user-info-container -->';
    }

    public function showUserInfoMain()
    {
        echo '<div class="user-info-container">';
        $this->UserInfoDoll();
        $this->userInfoStats(1);
        echo '</div><!-- user-info-container -->';
    }

    public function showStarSign()
    {
        /*
         * 1 aries
         * 2 taurus
         * 3 gemini
         * 4 cancer
         * 5 leo
         * 6 virgo
         * 7 libra
         * 8 scorpio
         * 9 sagittarios
         * 10 capricorn
         * 11 aquarius
         * 12 pisches
        */
        $zodiac[356] = "10";
        $zodiac[326] = "09";
        $zodiac[296] = "08";
        $zodiac[266] = "07";
        $zodiac[235] = "06";
        $zodiac[203] = "05";
        $zodiac[172] = "04";
        $zodiac[140] = "03";
        $zodiac[111] = "02";
        $zodiac[78] = "01";
        $zodiac[51] = "12";
        $zodiac[20] = "11";
        $zodiac[0] = "10";
        $dayOfYear = date("z", strtotime($this->borndate));
        $isLeapYear = date("L", strtotime($this->borndate)); //Высокосный?
        if ($isLeapYear && $dayOfYear > 59) {
            --$dayOfYear;
        }
        foreach ($zodiac as $day => $sign) {
            if ($dayOfYear > $day) {
                break;
            }
        }
        return $sign ?? null;
    }
}