<?php
# Date: 16.09.2020 (08:23)
// Магия лечения травм
namespace Battles\Magic;

use Battles\UserEffects, Battles\Database\Db, Battles\User;

class CureInjury extends Magic
{
    private $target;
    private $login;
    use UserEffects;

    /**
     * Магия лечения травм. Если у персонажа несколько травм, лечится самая тяжёлая.
     * @param int $target     - кого лечим.
     * @param int $injuryType - тип травмы, которую лечим. 11 лёгкая, 12 средняя, 13 тяжёлая, 14 неизлечимая, 15 все травмы.
     */
    public function __construct(int $target, int $injuryType)
    {
        $db = Db::getInstance();
        $this->target = $target;
        if (!$this->isUsable()) {
            return $this->status;
        }
        $ok = null;
        $injury = $db->ofetch('SELECT effect_id, type, name FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ? ORDER BY type DESC LIMIT 1', $target);
        if (in_array($injury->type, [11, 12, 13, 14]) && $injuryType >= $injury->type) {
            $db->execute('DELETE FROM users_effects WHERE effect_id = ?', $injury->effect_id);
            if (empty($injury->name) || $injury->name == 'Неизвестный эффект') {
                $injuryName = self::$effectName[$injury->type];
            } else {
                $injuryName = $injury->name;
            }
            $ok = "Вы вылечили повреждение ${injuryName} персонажу $this->login.";
        } elseif ($injury->effect_id && $injuryType == 15) {
            $db->execute('DELETE FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ?', $target);
            $ok = "Вы вылечили все повреждения персонажу $this->login.";
        }
        return $ok;
    }

    /**
     * Проверки на успех.
     * @return bool
     */
    private function isUsable(): bool
    {
        $this->target = $this->target == $_SESSION['uid'] ? User::getInstance() : User::getInstance($this->target);
        $this->login = $this->target->getLogin();
        return (
            $this->isVisible(User::getInstance(), $this->target) &&
            $this->isNotDead(User::getInstance()) &&
            $this->enoughMana(User::getInstance()) &&
            $this->isNotInBattle(User::getInstance())
        );
    }

    public static function cast($target, $type): self
    {
        return new self($target, $type);
    }
}