<?php
/**
 * Author: lopiu
 * Date: 06.07.2020
 * Time: 22:41
 */

namespace Battles;

use Battles\Database\Db;
use Battles\Models\Inventory;
use stdClass;

class DressedItems
{
    private int $userId;
    private stdClass $dressedItem;
    private static Db $db;
    private object $dressed;

    /**
     * DressedItems constructor.
     * @param int $userId ID игрока.
     */
    public function __construct(int $userId)
    {
        self::$db = Db::getInstance();
        $this->userId = $userId;
        $this->dressed = self::$db->ofetchAll('select * from inventory where dressed_slot > 0 and owner_id = ?', $this->userId);
    }

    public static function getDressedItemBySlot($itemSlot, $ownerId)
    {
        return self::$db->ofetch('SELECT *, COUNT(1) AS count FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]);
    }

    public function getItemsInSlots(): stdClass
    {
        $this->dressedItem = new stdClass();
        foreach ($this->dressed as $item) {
            $i = $item->dressed_slot;
            $this->dressedItem->$i = $item;
        }
        return $this->dressedItem;
    }

    /**
     * Снимает с предмета статус одетого на персонажа в определённом слоте персонажа.
     * @param $slotId - номер слота.
     */
    public function undressItem($slotId)
    {
        self::getItemsInSlots();
        // Проверяем, что используется один из 12 слотов и наличие предмета в слоте.
        if (in_array($slotId, Item::TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem->$slotId) {
            Inventory::undressOne($slotId, $this->userId);
        }
    }

    public static function undressAllItems($userId)
    {
        return self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot BETWEEN 1 AND 12 AND owner_id = ?', $userId);
    }

    public function checkRequirements()
    {
        $stats = (new UserStats($this->userId))->getFullStats();
        $q = 'select count(*) from inventory where
                dressed_slot > 0 and
                need_strength > ? and
                need_dexterity > ? and
                need_intuition > ? and
                need_endurance > ? and
                need_intelligence > ? and
                need_wisdom > ? and
                owner_id = ?';
        $args = [
            $stats->strength,
            $stats->dexterity,
            $stats->intuition,
            $stats->endurance,
            $stats->intelligence,
            $stats->wisdom,
            $this->userId
        ];
        if (self::$db->fetchColumn($q, $args) > 0) {
            self::undressAllItems($this->userId);
        }
    }
}