<?php

use Battle\Log;
use Core\Db;
use DarksLight2\Training\TrainingManager;
use Helper\Conversion;
use Helper\Math;
use Model\ActionModel;
use Model\Constant\Stat;
use User\Effects;

/*
- доделать добавление приема в $btl->users[]['eff'] после использования, в противном случаи некотрые приемы используются через 1 ход
*/

class Priems
{
    const FIRE = 'fire';
    const WATER = 'water';
    const AIR = 'air';
    const EARTH = 'earth';
    public $ue = [];
    private $btl;
    private $u;
    private $mname = [
        'огонь' => 1,
        'воздух' => 2,
        'вода' => 3,
        'земля' => 4,
        'свет' => 5,
        'тьма' => 6,
        'серая' => 7,
    ];
    private $logColor = [
        'crit' => '#f00',
        'miss' => '#888',
        self::FIRE => '#a00',
        self::WATER => '#00a',
        self::EARTH => '#0a0',
        self::AIR => '#0af',
    ];

    public function __construct(private readonly Stat $statnames = new Stat())
    {
        global $btl;
        $this->btl = $btl;
        $this->u = User::start();
        $this->statnames->getRequirement();
    }

    /** Набив Статики
     * @param int $uid если 0, будет использоваться id противника напротив.
     * @return void
     */
    public function addAirStaticPoints($uid = 0)
    {
        if ($uid == 0) {
            $uid = $this->ue['id'];
        }
        $x = Db::getValue(
            'select x from eff_users where uid = ? and `delete` = 0 and v2 = 260 and user_use = ? order by id desc limit 1',
            [$uid, $this->u->info['id']]
        );
        if (empty($x) || $x >= 5) {
            return;
        }
        $x++;
        $data['add_mg2static_points'] = $x;
        $data = Conversion::arrayToDataString($data);
        Db::sql(
            'update eff_users set x = ?, data = ? where uid = ? and `delete` = 0 and v2 = 260 and user_use = ?',
            [$x, $data, $uid, $this->u->info['id']]
        );
    }

    /** отнимаем ману
     * @param $uid
     * @param $mp
     * @param $tp [not used]
     * @return bool
     */
    public function minMana($uid, $mp, $tp = null)
    {
        global $btl;
        /* уменьшаем расход маны, если $mp > 0 */
        //с вычетом уменьшения разсхода маныss
        $mp -= round($mp / 100 * $btl->stats[$btl->uids[$uid]]['min_use_mp']);
        $btl->stats[$btl->uids[$uid]]['mpNow'] -= $mp;
        $mpNow = $this->zeromax($btl->stats[$btl->uids[$uid]]['mpNow'], $btl->stats[$btl->uids[$uid]]['mpAll']);
        if ($mpNow > 0) {
            Db::sql(
                'update stats set mpnow = ? where id = ?',
                [$btl->stats[$btl->uids[$uid]]['mpNow'], $uid]
            );
        }
        return $mpNow > 0;
    }

    private function zeromax($num, $max)
    {
        if ($num <= 0) {
            return 0;
        }
        if ($num > $max) {
            $num = $max;
        }
        return $num;
    }

    /** используем прием каждый ход
     * @param Battle $btl
     * @param array $eff
     * @return bool
     */
    public function hodUsePriem(Battle $btl, array $eff): bool
    {
        $u = $this->u; // Для присоедиянемых файлов.
        $pr = $eff['priem'];
        $return_main = true;
        $ue = Db::getRow(
            'select * from users left join stats on (users.id = stats.id) where users.id = ? and battle = ? and hpnow > 0',
            [$eff['uid'], $btl->i->id]
        );

        if (!empty($pr['file'])) {
            if (file_exists('../../_incl_data/class/priems/' . $pr['file'] . '.php')) {
                $hod = $eff['hod'];
                require_once 'priems/' . $pr['file'] . '.php';
            }
        } elseif (!empty($pr['file3'])) {
            if (file_exists('../../_incl_data/class/priems/' . $pr['file3'] . '.php')) {
                $hod = $eff['hod'];
                require_once 'priems/' . $pr['file3'] . '.php';
            }
        }
        return $return_main;
    }

    public function magicRegen($ue, $hpmin, $tmp, $pl, $eff, $rp = 0, $dp = 0, $krituet = true, $dopyrn = 0)
    {
        global $btl;
        $rr = [];
        $uen = $ue['id'];
        $usu = $eff['user_use'];
        if ($eff['user_use'] < 1) {
            $usu = $this->u->info['id'];
        }
        $k = $this->magKrit($ue['level'], $btl->stats[$btl->uids[$usu]]['mg' . $tmp]);

        if (!$krituet) {
            $k = 0;
        }

        $hpmin = $this->testPower($btl->stats[$btl->uids[$usu]], $btl->stats[$btl->uids[$uen]], $hpmin, $tmp, 2);
        $hpmin = round($hpmin);

        $dopyrn = $this->testPower($btl->stats[$btl->uids[$usu]], $btl->stats[$btl->uids[$uen]], $dopyrn, $tmp, 2);
        $dopyrn = round($dopyrn);

        if ($btl->users[$btl->uids[$uen]]['tactic7'] <= 0 && $dp == 0) {
            $hpmin = 0;
            $k = -1;
            $dopyrn = 0;
        }
        if ($k == 1 && $hpmin != 0 && $krituet) {
            //крит
            $hpmin = $hpmin * 2;
        } elseif ($k == -1 && $hpmin != 0) {
            //промах
            $hpmin = $hpmin / 2;
            $dopyrn = $dopyrn / 2;
        }
        if ($hpmin < 1) {
            $hpmin = 0;
        } else {
            $hpmin = rand(($hpmin * 0.97), $hpmin);
        }

        $hpmin += floor($dopyrn);

        if (isset($btl->stats[$btl->uids[$uen]]['min_heal_proc'])) {
            if ($btl->stats[$btl->uids[$uen]]['min_heal_proc'] > 100) {
                $btl->stats[$btl->uids[$uen]]['min_heal_proc'] = 100;
            }
            $hpmin = round($hpmin / 100 * (100 + $btl->stats[$btl->uids[$uen]]['min_heal_proc']));
        }

        if ($btl->users[$btl->uids[$uen]]['tactic7'] > 0 && $dp == 0) {
            //Отнимаем тактики, если это возможно
            $btl->users[$btl->uids[$uen]]['tactic7'] -= $hpmin / $btl->stats[$btl->uids[$uen]]['hpAll'];
            $btl->users[$btl->uids[$uen]]['tactic7'] = round($btl->users[$btl->uids[$uen]]['tactic7'], 2);
            $btl->stats[$btl->uids[$uen]]['tactic7'] = $btl->users[$btl->uids[$uen]]['tactic7'];
            if ($uen == $this->u->info['id']) {
                $this->u->info['tactic7'] = $btl->users[$btl->uids[$uen]]['tactic7'];
                $this->u->stats['tactic7'] = $btl->users[$btl->uids[$uen]]['tactic7'];
            }
            if ($btl->users[$btl->uids[$uen]]['tactic7'] < 0) {
                $btl->users[$btl->uids[$uen]]['tactic7'] = 0;
            }
        }
        $hp2 = floor($btl->stats[$btl->uids[$uen]]['hpNow'] + $hpmin);

        if ($hp2 > $btl->stats[$btl->uids[$uen]]['hpAll']) {
            $hpmin = floor($hp2 - $btl->stats[$btl->uids[$uen]]['hpAll']);
            $hp2 = $btl->stats[$btl->uids[$uen]]['hpAll'];
        } elseif ($hp2 < 0) {
            $hp2 = 0;
        }
        $rr[0] = $hpmin; //урон
        $rr[1] = $k; //тип
        /* проверяем приемы защиты */
        //получаем массив с приемами противника
        $miny = 0; //на сколько едениц урон буде меньше (защита приема)
        $minu = 0;
        $sp1 = mysql_query(
            'SELECT `e`.* FROM `eff_users` AS `e` WHERE `e`.`uid` = "' . $uen . '" AND `e`.`id_eff` = "22" AND `e`.`delete` = "0" AND `e`.`v1` = "priem" LIMIT 25'
        );
        while ($pl2 = mysql_fetch_assoc($sp1)) {
            $pl2['priem'] = mysql_fetch_assoc(
                mysql_query('SELECT * FROM `priems` WHERE `id` = "' . $pl2['v2'] . '" LIMIT 1')
            );
            if (isset($pl2['priem']['id'])) {
                $dt1 = Conversion::dataStringToArray($pl2['priem']['date2']);
                if (isset($dt1['yron_u2'])) {

                    $minu = $this->getdr(
                        $dt1['yron_u2'], [0 => 'lvl1', 1 => 'yr1', 2 => 'ts5', 3 => 'ts6'],
                        [0 => $btl->users[$btl->uids[$level]], 1 => $hpmin, 2 => 0, 3 => 0]
                    );
                    $miny -= $minu;
                    $hpmin += $minu;
                    $btl->delPriem($pl2, $btl->users[$btl->uids[$uen]]);
                }
            }
        }

        /* проверяем приемы ослабления */

        //отнимаем НР
        $btl->users[$btl->uids[$uen]]['hpNow'] = $hp2;
        $btl->stats[$btl->uids[$uen]]['hpNow'] = $hp2;
        mysql_query(
            'UPDATE `stats` SET `hpNow` = ' . $hp2 . ',`tactic7` = ' . $btl->users[$btl->uids[$uen]]['tactic7'] . ' WHERE `id` = "' . $uen . '" LIMIT 1'
        );

        //заносим в лог боя
        $vLog =
            'time1=' . time() .
            '||s1=' . $this->u->info['sex'] .
            '||t1=' . $this->u->info['team'] .
            '||login1=' . $this->u->info['login'] .
            '||s2=' . $btl->users[$btl->uids[$uen]]['sex'] .
            '||t2=' . $btl->users[$btl->uids[$uen]]['team'] .
            '||login2=' . $btl->users[$btl->uids[$uen]]['login'];
        $mas1 = [
            'time' => time(),
            'battle' => $btl->i->id,
            'id_hod' => ($btl->hodID + 1),
            'text' => '',
            'vars' => $vLog,
            'zona1' => '',
            'zonb1' => '',
            'zona2' => '',
            'zonb2' => '',
            'type' => '1',
        ];
        if ($rp == 1) {
            $mas1['id_hod']--;
        }

        $btl->takeExp($this->u->info['id'], ($hpmin * 0.33), $this->u->info['id'], $uen, true);

        if ($hpmin > 0) {
            $hpmin = '+' . ceil($hpmin);
        } else {
            $hpmin = '--';
        }
        $tco = [1 => '006699', 2 => '006699', 3 => '006699', 4 => '006699']; //не крит
        $tcl = [1 => 'A00000', 2 => '008080', 3 => '0000FF', 4 => 'A52A2A']; //не крит
        $tco = $tco[$tmp];
        $tcl = $tcl[$tmp];
        if ($k == 1) {
            //крит
            $tco = 'FF0000';
            $tcl = 'FF0000';
        } elseif ($k == -1) {
            //промах
            $tco = '979797';
            $tcl = '979797';
        }
        $nmz = [
            1 => [0 => 'огня', 1 => 'огненная'],
            2 => [0 => 'воздуха', 1 => 'электрическая'],
            3 => [0 => 'воды', 1 => 'водная'],
            4 => [0 => 'земли', 1 => 'земляная'],
        ];
        $nmz = $nmz[$tmp];

        if ($rp == 1) {
            $sx = [0 => '', 1 => 'а'];
            $mas1['text'] = '{tm1} Заклинание &quot;<b><font color=#' . $tcl . '>' . $pl['name'] . '</font></b>&quot; восстановило здоровье персонажа {u2}. <b><font title=Тип&nbsp;регенерации:&nbsp;' . $nmz[1] . ' color=#' . $tco . '>' . $hpmin . '</font></b> [' . ceil(
                    $hp2
                ) . '/' . $btl->stats[$btl->uids[$uen]]['hpAll'] . ']';
        } else {
            $mas1['text'] = '{tm1} {u1} {1x16x0} заклинание &quot;<b><font color=#' . $tcl . '>' . $pl['name'] . '</font></b>&quot; и восстановил здоровье персонажа {u2} магией ' . $nmz[0] . '. <b><font title=Тип&nbsp;регенерации:&nbsp;' . $nmz[1] . ' color=#' . $tco . '>' . $hpmin . '</font></b> [' . ceil(
                    $hp2
                ) . '/' . $btl->stats[$btl->uids[$uen]]['hpAll'] . ']';
        }

        Log::add($mas1);
        $pz[(int)$id] = 1;
        return $rr;
    }

    /** Какой-то нестандартный частный расчет маг.крита
     * @param $l2
     * @param $t
     * @return int
     */
    public function magKrit($l2, $t)
    {
        $r = $l2 * 2 - 7;
        if ($r > $t) {
            //магический промах (серый удар, в 2 раза меньше) 6%
            //250 ед. защиты от магии дает 1% шанса увернуться от магии
            //$r = -1; , промах --
            $r = 0;
        } else {
            //каждая владелка дает 3% шанс крита
            $r = ceil($t * 0.75);
            if ($r > 30) {
                $r = 30;
            }
            if (rand(0, 10000) < $r * 100) {
                //крит удар
                $r = 1;
            } else {
                $r = 0;
            }
        }
        return $r;
    }

    public function testPower($s1, $s2, $y, $t, $t2)
    {
        global $u, $btl;

        $r = 0;
        if ($t2 == 2) {
            //урон магией
            $pm = [0 => 0, 1 => 0, 2 => 0, 3 => 0];
            if ($t < 5) {
                $pm[0] = $s1['m11'];
                $pm[1] = $s2['zm'];
                $pm[2] = $s2['antm11'];
            }

            if (isset($btl->i->id)) {
                $pm[3] = $btl->zmgo($s2['zm' . $t]);
                $pm[3] = round($pm[3]);
            }

            //урон = b*(1+m/100)*2^((p*10-z)/k)
            $fx_vl = [
                250,
                250,
                250,
                250,
                250,
                250,
                250,
                250,
                250,
                350,
                400,
                450,
                500,
                550,
                600,
                650,
                700,
                750,
                800,
                850,
                900,
                950,
            ];

            $fx = [
                'b' => $y, //базовый урон
                'm' => round($s1['pm' . $t] * 1 - $s2['antpm' . $t]), //мощь
                'z' => round($s2['zm' . $t]), //защита цели ед.
                'p' => round(($s1['pzm'] + $s1['pzm' . $t])), //подавление
                'k' => $fx_vl[(0 + $s1['lvl'])], //коэффициент ; k=250 для 8ки, k=300 для 9ки и т.д. +20% на уровень
            ];
            if (($fx['z'] + 250) - $fx['p'] * 10 < 0) { //защита не может уйти больше, чем в 250 ед.
                $fx['p'] = ($fx['z'] + 250) / 10;
            }
            $fx['p'] = 0;
            //
            $p = $fx['b'] * (1 + $fx['m'] / 100) * pow(2, (($fx['z'] - $fx['p'] * 10) / $fx['k']));
            //$p += $p/100*10;
            $p -= $p / 100 * $pm[3];
            //$p += floor($s1['s5']*0.25);

            if ($p < round($y * 0.1)) {
                $p = round($y * 0.1);
            } elseif ($p > round($y * 10)) {
                $p = $y * 10;
            }

            if (isset($s2['zm' . $t . 'proc'])) //защита от магии стихий (призрачки)
            {
                $p = floor($p / 100 * (100 - $s2['zm' . $t . 'proc']));
                if ($p < 0) {
                    $p = 0;
                }
            }
            if (isset($s2['zmproc'])) //защита от магии стихий (призрачки)
            {
                if ($s2['zmproc'] >= 75) {
                    $p = floor($p / 100 * (100 - 75));
                } else {
                    $p = floor($p / 100 * (100 - $s2['zmproc']));
                    if ($p < 0) {
                        $p = 0;
                    }
                }
            }
            $r = $p;
        }

        return round($r / 100 * 70);
    }

    /**@deprecated try to use getDynamicInfo() */
    private function getdr($s, $v, $d)
    {
        $i = 0;
        while ($i < count($v)) {
            if (isset($v[$i])) {
                $s = str_replace('{' . $v[$i] . '}', $d[$i], $s);
            }
            $i++;
        }
        $s = eval("return (" . $s . ");");
        return floor($s);
    }

    /* uid - на кого кастуем
	   pr - id приема
	   data - дата, если -1, то добавляем дату3
	   d2 - добавляем дату3
	   tm - время использования, 77 - вечно
	   h - кол-во "вечных" ходов
	   uu - id юзера который использовал
	   tp - тип приема
	*/

    /** Оставлена для совместимости. На неё ссылается куча всего. */
    public function magatack($u1, $u2, $yron, $type, $krit)
    {
        global $btl;
        return $this->magicAttack($btl, $u1, $u2, $yron, $type, $krit);
    }

    /**
     * Новая функция магического заклинания с приёма.
     * Работает с числовыми приёмами в папке [priem].
     * @param int $attackerId кто использует приём
     * @param int $defenderId на кого использует приём
     * @param float $damage базовый урон приёма
     * @param string $damageType тип урона (стихия?) приходит строкой, и конвертируется функцией.
     * @param bool $hasCritical флаг, что приём МОЖЕТ критовать
     * @return array [0|damage] int урон, [1|crit] bool был ли крит, [2|miss] bool был ли промах, [3|miss_type] int тип промаха (всегда = 2).
     * @author Insallah
     */
    public function magicAttack(Battle $btl, $attackerId, $defenderId, $damage, $damageType, $hasCritical = false)
    {
        // Не так паршиво как прошлая, но всё ещё паршиво. Теперь хоть что-то понять можно.
        $dmgRuNames = [
            self::FIRE => 'огонь',
            self::WATER => 'вода',
            self::AIR => 'воздух',
            self::EARTH => 'земля',
        ];
        if (in_array($damageType, array_keys($dmgRuNames))) {
            $damageType = $dmgRuNames[$damageType];
        }

        // Мощь.
        // pm# = Мф. мощности магии определенного типа
        // m11  = Мф. мощности магии стихий
        // m11a = Мф. мощности магии
        // ОКАЗЫВАЕТСЯ [pm# = m11 + m11a] где-то выше по коду!
        $power = $btl->stats[$btl->uids[$attackerId]]['pm' . $this->mname[$damageType]];

        // Подавление в процентах.
        $suppression = 0;
        $suppression += $btl->stats[$btl->uids[$attackerId]]['pzm'];
        // Уязвимость магии стихий, из приёма 250.
        $suppression += $btl->stats[$btl->uids[$attackerId]]['yzm'];

        // Сколько у использующего умений числом.
        $skills = $btl->stats[$btl->uids[$attackerId]]['mg' . $this->mname[$damageType]];

        // Защита цели числом
        // zm# = Защита от магии определенного типа
        // zm  = Защита от магии стихий
        // zma = Защита от магии
        // ОКАЗЫВАЕТСЯ [zm# = zm + zma] где-то выше по коду!
        $defence = $btl->stats[$btl->uids[$defenderId]]['zm' . $this->mname[$damageType]];

        // Минимум умений для 100% успеха приёма.
        // У 8 екро-мага со старта 20, это очень много: 8 бьёт 10 без промаха.
        $requiredSkills = $btl->users[$btl->uids[$defenderId]]['level'] * 2;

        // Чёртово "Следующий каст будет критическим".
        $isGarantCrit = $btl->stats[$btl->uids[$attackerId]]['acestar'] > 0;

        // Подавляем защиту, понижая число на процент подавления.
        $supressedDefence = Math::addPercent($defence, -min($suppression, 100));

        // Урон зависит от умений и уровня противника.
        $damage *= $skills - $requiredSkills;

        // Увеличиваем урон, повышая число на мощь если урон > 0.
        $poweredDamage = $damage > 0 ? $damage + $power : 0;

        // Шанс крита равен уровню магического навыка
        $isCritical = $hasCritical && $skills >= mt_rand(0, 100);

        if ($isGarantCrit) {
            $isCritical = true;
            Db::sql(
                'delete from eff_users where uid = ? and `delete` = 0 and data like ?',
                [$attackerId, '%add_acestar%']
            );
            unset($q);
        }

        if ($skills >= $requiredSkills || $isCritical) {
            $isHit = true;
        } else {
            $isCritical = false;
            $missChance = 3 * ($requiredSkills - $skills);
            $isHit = mt_rand(0, 100) > $missChance;
        }

        // Для совместимости. Старая функция возвращает это значение, вдруг оно где-то используется.
        $pType = 0;
        if ($isHit) {
            // Урон = Повреждения - Защита, но не меньше 0. Округлено до целых.
            //$finalDamage = max(round(Math::addPercent($poweredDamage, -$supressedDefence)), 0);
            $finalDamage = $poweredDamage - $supressedDefence;
            if ($isCritical) {
                $finalDamage *= 2;
            }
        } else {
            $finalDamage = 0;
            // Для совместимости. Старая функция возвращает это значение, вдруг оно где-то используется.
            $pType = 2;
        }

        // Призрачки, режут конечный урон после вычета защиты.
        $ghostDefences = $this->hasGhostDefence($defenderId);
        if ($ghostDefences['all']) {
            $finalDamage /= 4;
        }

        // Костыль для призрачек. Когда вызовы русских стихий уберутся, будет не нужен.
        if (in_array($damageType, $dmgRuNames)) {
            $damageType = array_search($damageType, $dmgRuNames);
        }

        if ($ghostDefences[$damageType]) {
            $finalDamage /= 2;
        }

        $finalDamage = max(round($finalDamage), 0);

        // Для отладки.
        if ($btl->users[$btl->uids[$attackerId]]['admin'] > 0) {
            $s = "Подавление защиты: $suppression%, Бонус урона: $power, Навыки: $skills, 
            <br> Усиление урона от уровня и скилла: damage x ($skills - $requiredSkills)<br> $damageType 
            Его Защита: ($defence -$suppression%) = $supressedDefence | 
            Мой Урон: ($damage +$power) = $poweredDamage<br> 
            Мой Удар: ($poweredDamage -$supressedDefence) = $finalDamage";
            $s .= $isCritical ? ' (крит *2)' : '';
            echo "<div style='background-color: #C5C5C5; border: 1px solid coral; margin-top: 15px;'>$s</div>";
        }


        // !isHit потому что прошлая функуция возвращала Промах.
        // pType ни на что не влияет, = 0 и просто становится = 2 при промахе. Зачем - загадка.
        // -damage потому что где-то дальше код разворачивает результат меняя ему знак.
        return [
            (int)$finalDamage,
            $isCritical,
            !$isHit,
            $pType,    // для совместимости
            'damage' => (int)$finalDamage,
            'crit' => $isCritical,
            'miss' => !$isHit,
            'miss_type' => $pType,
        ];
    }

    /** Проверка есть ли на персонаже призрачные защиты для рассчёта урона через magicAttack
     * @return array
     */
    private function hasGhostDefence($uid)
    {
        $def = [
            'all' => false,
            self::FIRE => false,
            self::AIR => false,
            self::EARTH => false,
            self::WATER => false,
        ];
        $priems = Db::getRows('select v2 from eff_users where uid = ? and v2 in (141, 142, 144, 145, 146)', [$uid]);
        foreach ($priems as $priem) {
            if ($priem['v2'] == 141) {
                $def['all'] = true;
            }
            if ($priem['v2'] == 142) {
                $def[self::FIRE] = true;
            }
            if ($priem['v2'] == 144) {
                $def[self::AIR] = true;
            }
            if ($priem['v2'] == 145) {
                $def[self::WATER] = true;
            }
            if ($priem['v2'] == 146) {
                $def[self::EARTH] = true;
            }
        }
        return $def;
    }

    public function magatackfiz($u1, $u2, $yron, $type, $krit, $ymelki)
    {
        global $btl;
        $cof_mag = [
            0 => 250,
            1 => 250,
            2 => 250,
            3 => 250,
            4 => 250,
            5 => 250,
            6 => 250,
            7 => 250,
            8 => 250,
            9 => 300,
            10 => 360,
            11 => 475,
            12 => 520,
            13 => 625,
            14 => 750,
            15 => 895,
            16 => 1075,
            17 => 1290,
            18 => 1550,
            19 => 1860,
            20 => 2230,
            21 => 2675,
        ];

        $r = $yron;
        //
        if (!isset($ymelki) || $ymelki == '0') {
            $ymelki = $type;
        }
        //
        $prm = [
            'ym' => $btl->stats[$btl->uids[$u1]]['mg' . $this->mname[$ymelki]], //умелки (магические умелки)
            'y' => $btl->stats[$btl->uids[$u1]]['a' . $this->mname[$ymelki]], //умелки
            'yv' => 0, //умения, значение коф.
            'max_krit' => 0, //вероятность крита
        ];
        //
        // (уровень цени)*2 - 7 - минимальное умелок, чтобы не было промахов
        /*
		Для магии Света/Тьмы по формуле: Уровень Цели * 2 – 9
		каждая умелка выше этой нормы увеличивает маг крит на 3%. но не больше 30%
		*/
        //Рассчет урона от приема
        /*
		b - базовый урон
		m - мощь
		z - защита цели [ед.]
		p - подавление [ед.]
		k - коэффициент ; k=250 для 8ки, k=300 для 9ки и т.д. +20% на уровень
		*/
        $prm['b'] = $r; //базовый урон
        $prm['m'] = $btl->stats[$btl->uids[$u1]]['pa' . $this->mname[$type]]; //мощь
        $prm['z'] = $btl->stats[$btl->uids[$u2]]['za' . $this->mname[$type]]; //защита цели (ед.)
        $prm['p'] = $btl->stats[$btl->uids[$u1]]['pza' . $this->mname[$type]]; //подавление (ед.)
        $prm['k'] = $cof_mag[$btl->users[$btl->uids[$u1]]['level']]; //коэффицент
        //
        if ($prm['p'] * 10 > $prm['k']) {
            $prm['p'] = floor($prm['k'] / 10);
        }
        //
        $r = $prm['b'] * (1 + $prm['m'] / 100) * pow(2, (($prm['p'] * 10 - $prm['z']) / $prm['k']));
        if ($r < floor($prm['b'] * 0.2)) {
            $r = floor($prm['b'] * 0.2);
        } elseif ($r > floor($prm['b'] * 10)) {
            $r = floor($prm['b'] * 10);
        }
        //
        //$prm['y'] -= 5;
        if ($type < $this->mname[$type]) {
            $prm['yv'] = ($btl->users[$btl->uids[$u2]]['level'] * 2 - 7);
        } else {
            $prm['yv'] = ($btl->users[$btl->uids[$u2]]['level'] * 2 - 9);
        }
        //
        if ($prm['y'] >= $prm['yv'] || (isset($this->mname[$ymelki]) && $prm['ym'] >= $prm['yv'])) {
            if ($krit == 1) {
                if (isset($this->mname[$ymelki])) {
                    $prm['max_krit'] = 3 * ($prm['ym'] - $prm['yv']);
                } else {
                    $prm['max_krit'] = 3 * ($prm['y'] - $prm['yv']);
                }
                //echo '[Magical crit: '.$prm['max_krit'].'%]';
                if ($prm['max_krit'] < 0) {
                    $prm['max_krit'] = 0;
                } elseif ($prm['max_krit'] > 30) {
                    $prm['max_krit'] = 30;
                }
                //$prm['max_krit'] = round($prm['max_krit']/2);
                //Крит возможен
                if (rand(0, 100) <= $prm['max_krit']) {
                    $krit = true;
                } else {
                    $krit = false;
                }
            } else {
                $krit = false;
            }
            $promah = false;
        } else {
            $krit = false;
            //Вероятность промоха
            $prm['promah'] = 3 * ($prm['yv'] - $prm['ym']);
            if ($prm['promah'] < 0) {
                $prm['promah'] = 0;
            } elseif ($prm['promah'] > 30) {
                $prm['promah'] = 30;
            }
            if (rand(0, 100) <= $prm['promah']) {
                $promah = true;
            } else {
                $promah = false;
            }
        }
        //
        if ($krit) {
            $r = $r * 2;
            $promah_type = 0;
        } elseif ($promah) {
            $r = rand(1, floor($r / 4));
            $promah_type = 1;
            if (rand(0, 100) < 50) {
                $r = 0;
                $promah_type = 2;
            }
        }
        //
        unset($prm);
        //
        return [floor($r), $krit, $promah, $promah_type];
    }

    public function magicAtack(
        $ue,
        $hpmin,
        $tmp,
        $pl,
        $eff,
        $rp = 0,
        $mxx = 0,
        $fiz = 0,
        $nomf = 0,
        $krituet = true,
        $heal = 0,
        $namenew = null
    )
    {
        $trawm_off = false;
        global $btl;
        if ($namenew != null) {
            $pl['name'] = $namenew;
        }
        $rr = [];
        $nhpmin = $hpmin;
        $uen = $ue['id'];
        $usu = $eff['user_use'];
        if ($eff['user_use'] < 1) {
            $usu = $this->u->info['id'];
        }
        if ($nomf == 0) {
            $k = $this->magKrit($ue['level'], $btl->stats[$btl->uids[$usu]]['mg' . $tmp]);
            if (!$krituet) {
                $k = 0;
            }
            if ($fiz == 0) {
                //магический урон
                $hpmin = $this->testPower(
                    $btl->stats[$btl->uids[$usu]], $btl->stats[$btl->uids[$uen]], $hpmin, $tmp,
                    2
                );
            } else {
                //физический урон
                $wAp = $btl->stats[$btl->uids[$usu]]['pa' . $tmp . ''];
                $wAp += $btl->stats[$btl->uids[$usu]]['m10'];
                $wAp -= $btl->stats[$btl->uids[$uen]]['antpa' . $tmp . ''] * 1.75;
                $wAp -= $btl->stats[$btl->uids[$uen]]['antm10'] * 1.75;
                $hpmin += ceil((0.01 + $hpmin / 100) * (0.01 + 0.98 * $wAp)) - 1;

                $hpmin -= round(
                    $hpmin / 100 * (35 * ($btl->stats[$btl->uids[$uen]]['za'] + $btl->stats[$btl->uids[$uen]]['za' . $tmp]) / 1200)
                );
                $hpmin = round($hpmin);

                if (isset($btl->stats[$btl->uids[$uen]]['zaproc']) || isset($btl->stats[$btl->uids[$uen]]['za' . $fiz . 'proc'])) //защита от урона (призрачки)
                {
                    $hpmin = floor(
                        $hpmin / 100 * (100 - $btl->stats[$btl->uids[$uen]]['zaproc'] - $btl->stats[$btl->uids[$uen]]['za' . $fiz . 'proc'])
                    );
                    if ($hpmin < 0) {
                        $hpmin = 0;
                    }
                }
            }
        }
        $hpmin = round($hpmin);
        if ($k == 1 and $krituet) {
            //крит
            $hpmin = $hpmin * 2;
        } elseif ($k == -1) {
            //промах
            $hpmin = $hpmin / 2;
        }
        if ($hpmin < $nhpmin * 0.2) {
            $hpmin = $nhpmin * 0.2;
        }
        if ($hpmin < 1) {
            $hpmin = 0;
        } else {
            if ($nomf == 0) {
                $hpmin = rand(($hpmin * 0.97), $hpmin);
            }
        }
        if ($mxx > 0 && $hpmin > $mxx) {
            if ($k == 0) {
                $hpmin = $mxx;
            } elseif ($k == 1 && $hpmin / 2 > $mxx) {
                $hpmin = $mxx * 2;
            }
        }
        $rr[0] = $hpmin; //урон
        $rr[1] = $k; //тип
        /* проверяем приемы защиты */
        //получаем массив с приемами противника
        $miny = 0; //на сколько едениц урон буде меньше (защита приема)
        $sp1 = mysql_query(
            'SELECT `e`.* FROM `eff_users` AS `e` WHERE `e`.`uid` = "' . $uen . '" AND `e`.`id_eff` = "22" AND `e`.`delete` = "0" AND `e`.`v1` = "priem" LIMIT 25'
        );
        while ($pl2 = mysql_fetch_assoc($sp1)) {
            $pl2['priem'] = mysql_fetch_assoc(
                mysql_query('SELECT * FROM `priems` WHERE `id` = "' . $pl2['v2'] . '" LIMIT 1')
            );
            if (isset($pl2['priem']['id'])) {
                $dt1 = Conversion::dataStringToArray($pl2['priem']['date2']);
                if (isset($dt1['yron_u2'])) {
                    $minu = $this->getdr(
                        $dt1['yron_u2'], [0 => 'lvl1', 1 => 'yr1', 2 => 'ts5', 3 => 'ts6'],
                        [0 => $btl->users[$btl->uids[$level]], 1 => $hpmin, 2 => 1, 3 => 0]
                    );
                    $miny -= $minu;
                    $hpmin += $minu;
                    if (isset($dt1['rzEndMg']) && $dt1['rzEndMg'] == 1) {
                        $btl->delPriem($pl2, $btl->users[$btl->uids[$uen]]);
                    }
                } elseif (isset($dt1['rzEndMg']) && $dt1['rzEndMg'] == 1) {
                    $btl->delPriem($pl2, $btl->users[$btl->uids[$uen]]);
                }
            }
        }

        $hpmin = $btl->testPogB($uen, $hpmin);

        $hp2 = floor($btl->stats[$btl->uids[$uen]]['hpNow'] - $hpmin);

        if ($btl->stats[$btl->uids[$usu]]['yrnhealmpprocmg' . $tmp] > 0 && $fiz == 0) {
            //Часть урона восставнавливает ману
            $btl->stats[$btl->uids[$usu]]['mpNow'] += round(
                $hpmin / 100 * $btl->stats[$btl->uids[$usu]]['yrnhealmpprocmg' . $tmp]
            );
            //if($btl->stats[$btl->uids[$usu]]['mpNow'] > $btl->stats[$btl->uids[$usu]]['mpAll']) {
            //$btl->stats[$btl->uids[$usu]]['mpNow'] = $btl->stats[$btl->uids[$usu]]['mpAll'];
            //}
            $btl->users[$btl->uids[$usu]]['mpNow'] = $btl->stats[$btl->uids[$usu]]['mpNow'];
            if ($usu == $this->u->info['id']) {
                $this->u->info['mpNow'] = $btl->stats[$btl->uids[$usu]]['mpNow'];
                $this->u->stats['mpNow'] = $btl->stats[$btl->uids[$usu]]['mpNow'];
            }
        }

        if ($hp2 < 0) {
            $hp2 = 0;
        } elseif ($hp2 > $btl->stats[$btl->uids[$uen]]['hpAll']) {
            $hp2 = $btl->stats[$btl->uids[$uen]]['hpAll'];
        }

        $btl->stats[$btl->uids[$uen]]['last_hp'] = -floor($hpmin);

        if ($heal != 0) {
            if ($heal == -1) {
                //хил на текущий урон с учетом мф
                $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] += $hpmin;
                if ($btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] < 0) {
                    $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] = 0;
                } elseif ($btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] > $btl->stats[$btl->uids[$eff['user_use']]]['hpAll']) {
                    $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] = $btl->stats[$btl->uids[$eff['user_use']]]['hpAll'];
                }

                if ($eff['user_use'] == $this->u->info['id']) {
                    $this->u->stats['hpNow'] = $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'];
                }

                $btl->users[$btl->uids[$eff['user_use']]]['hpNow'] = $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'];

                mysql_query(
                    'UPDATE `stats` SET `hpNow` = "' . $btl->stats[$btl->uids[$eff['user_use']]]['hpNow'] . '" WHERE `id` = "' . $eff['user_use'] . '" LIMIT 1'
                );
            } else {
                //хил на конкретное число

            }
        }

        /* проверяем приемы ослабления */

        //отнимаем НР
        $btl->users[$btl->uids[$uen]]['hpNow'] = $hp2;
        $btl->stats[$btl->uids[$uen]]['hpNow'] = $hp2;

        if ($uen == $this->u->info['id']) {
            $this->u->stats['hpNow'] = $hp2;
        }

        // тяж травма для кровавых
        if ($btl->i->type == 99 and $hp2 == 0 and !$trawm_off) {
            //$eff['user_use']
            //$sp1 = mysql_query('SELECT `e`.* FROM `eff_users` AS `e` WHERE `e`.`uid` = "'.$uen.'" AND `e`.`id_eff` = "22" AND `e`.`delete` = "0" AND `e`.`v1` = "priem" LIMIT 25');

            $trawm_off = true;
            //$at[2][$i]['ttravm']='получил <font color=red><b>Тяжелую травму</b></font>.';
            Effects::addInjury($btl->users[$btl->uids[$uen]]['id'], 3, $btl->users[$btl->uids[$eff['user_use']]]['level']);
        }
        $upd = mysql_query(
            'UPDATE `stats` SET `hpNow` = ' . $hp2 . ',`last_hp` = "' . $btl->stats[$btl->uids[$uen]]['last_hp'] . '" WHERE `id` = "' . $uen . '" LIMIT 1'
        );

        //заносим в лог боя
        $vLog = 'time1=' . time() . '||s1=' . $btl->users[$btl->uids[$usu]]['sex'] . '||t1=' . $btl->users[$btl->uids[$usu]]['team'] . '||login1=' . $btl->users[$btl->uids[$usu]]['login'] . '||s2=' . $btl->users[$btl->uids[$uen]]['sex'] . '||t2=' . $btl->users[$btl->uids[$uen]]['team'] . '||login2=' . $btl->users[$btl->uids[$uen]]['login'] . '';
        $mas1 = [
            'time' => time(),
            'battle' => $btl->i->id,
            'id_hod' => ($btl->hodID + 1),
            'text' => '',
            'vars' => $vLog,
            'zona1' => '',
            'zonb1' => '',
            'zona2' => '',
            'zonb2' => '',
            'type' => '1',
        ];
        if ($rp > 0) {
            $mas1['id_hod']--;
        }
        $hpminkrit = 0;
        if ($k == 1) {
            $hpminkrit = $hpmin;
        }
        $btl->addNewStat(
            [
                'battle' => $this->u->info['battle'],
                'uid1' => $this->u->info['id'],
                'uid2' => $uen,
                'time' => time(),
                'type' => 0,
                'a' => '10000',
                'b' => 0,
                'type_a' => 1,
                'type_b' => 0,
                'ma' => 1,
                'mb' => 1,
                'yrn' => $hpmin,
                'yrn_krit' => $hpminkrit,
                'tm1' => $this->u->info['team'],
                'tm2' => $btl->users[$btl->uid[$uen]]['team'],
            ]
        );

        $btl->takeExp($this->u->info['id'], $hpmin, $usu, $uen);

        if ($hpmin > 0) {
            $hpmin = '-' . ceil($hpmin);
        } else {
            $hpmin = '--';
        }
        $tco = [
            1 => '006699',
            2 => '006699',
            3 => '006699',
            4 => '006699',
            5 => '006699',
            6 => '006699',
            7 => '006699',
        ]; //не крит
        $tcl = [
            1 => 'A00000',
            2 => '008080',
            3 => '0000FF',
            4 => 'A52A2A',
            5 => '006699',
            6 => '006699',
            7 => '006699',
        ]; //не крит
        $tco = $tco[$tmp];
        $tcl = $tcl[$tmp];
        if ($k == 1) {
            //крит
            $tco = 'FF0000';
            $tcl = 'FF0000';
        } elseif ($k == -1) {
            //промах
            $tco = 'CCCCCC';
            $tcl = 'CCCCCC';
        }
        $nmz = [
            1 => [0 => 'огня', 1 => 'огненный'],
            2 => [0 => 'воздуха', 1 => 'электрический'],
            3 => [0 => 'воды', 1 => 'холод'],
            4 => [0 => 'земли', 1 => 'земляной'],
            5 => [0 => 'Свет', 1 => 'Свет'],
            6 => [0 => 'Тьма', 1 => 'Тьма'],
            7 => [0 => 'Серая&nbsp;магия', 1 => 'Серая&nbsp;магия'],
        ];
        $nmz = $nmz[$tmp];
        if ($fiz > 0) {
            $nmz = [
                1 => [0 => ', колющая атака , ', 1 => 'колющий'],
                2 => [0 => ', рубящая атака , ', 1 => 'рубящий'],
                3 => [0 => ', дробящая атака , ', 1 => 'дробящий'],
                4 => [0 => ', режущая атака , ', 1 => 'режущий'],
            ];
            $nmz = $nmz[$fiz];
        }

        if ($rp == 1) {
            if ($k == 0) {
                $tcl = '000000';
                $tco = '008000';
            }
            $sx = [0 => '', 1 => 'а'];
            $mas1['text'] = '{tm1} {u2} утратил' . $sx[$btl->users[$btl->uids[$uen]]['sex']] . ' здоровье от &quot;<b><font color=#' . $tcl . '>' . $pl['name'] . '</font></b>&quot;. <b><font title=Тип&nbsp;урона:&nbsp;' . $nmz[1] . ' color=#' . $tco . '>' . $hpmin . '</font></b> [' . ceil(
                    $hp2
                ) . '/' . $btl->stats[$btl->uids[$uen]]['hpAll'] . ']';
        } else {
            if ($fiz == 1) {
                $mas1['text'] = '{tm1} {u1} {1x16x0} прием &quot;<b><font color=#' . $tcl . '>' . $pl['name'] . '</font></b>&quot; и поразил {u2}. <b><font title=Тип&nbsp;урона:&nbsp;' . $nmz[1] . ' color=#' . $tco . '>' . $hpmin . '</font></b> [' . ceil(
                        $hp2
                    ) . '/' . $btl->stats[$btl->uids[$uen]]['hpAll'] . ']';
            } else {
                $mas1['text'] = '{tm1} {u1} {1x16x0} заклинание &quot;<b><font color=#' . $tcl . '>' . $pl['name'] . '</font></b>&quot; и поразил магией ' . $nmz[0] . ' {u2}. <b><font title=Тип&nbsp;урона:&nbsp;' . $nmz[1] . ' color=#' . $tco . '>' . $hpmin . '</font></b> [' . ceil(
                        $hp2
                    ) . '/' . $btl->stats[$btl->uids[$uen]]['hpAll'] . ']';
            }
        }

        Log::add($mas1);
        $pz[(int)$id] = 1;
        return $rr;
    }

    public function pruse($id): void
    {
        global $btl;
        if ($id == 100500 && $this->u->info['animal'] > 0) {
            $this->processAnimal($btl);
        } else {
            $this->processPriem($id, $btl);
        }
    }

    private function processAnimal(Battle $btl): void
    {
        if ($this->u->stats['hpNow'] < 1) {
            echo 'Вы не можете выпустить зверя, вы потеряли все НР';
            return;
        }

        $alreadyReleased = ActionModel::testCount(["uid = {$this->u->info['id']}", "vars = animal_use{$btl->i->id}"]);

        if (!empty($alreadyReleased)) {
            echo 'Вы уже выпускали зверя в этом бою ...';
            return;
        }

        $animal = Db::getRow('select * from users_animal where uid = ? and id = ? and pet_in_cage = 0', [$this->u->info['id'], $this->u->info['animal']]);

        if (!isset($animal['id'])) {
            echo 'У вас нет зверя.';
            return;
        }

        if ($animal['eda'] < 1) {
            echo 'Вы не накормили зверя.';
            return;
        }

        $animalTypes = [
            1 => 'Кот',
            2 => 'Сова',
            3 => 'Светляк',
            4 => 'Чертяка',
            5 => 'Пес',
            6 => 'Свин',
            7 => 'Дракон',
        ];

        $botLogin = $animalTypes[$animal['type']] . ' [' . $animal['level'] . ']';
        $botId = Db::getValue('select id from test_bot where login = ?', [$botLogin]);

        if (!$botId) {
            echo 'Системная ошибка: Неизвестный зверь!';
            return;
        }

        $b = $this->u->addNewbot($botId);

        if (!$b) {
            echo 'Не удалось призвать зверя.';
            return;
        }

        if ($b > 0) {
            $animal['eda'] -= 4;
            if ($animal['eda'] < 0) {
                $animal['eda'] = 0;
            }

            $logData = [
                'time' => time(),
                'battle' => $btl->i->id,
                'id_hod' => $btl->hodID,
                'vars' => 'time1=' . time() . '||s1=' . $this->u->info['sex'] . '||t1=' . $this->u->info['team'] . '||login1=' . $this->u->info['login'],
                'zona1' => '',
                'zonb1' => '',
                'zona2' => '',
                'zonb2' => '',
                'type' => '1',
                'text' => '{tm1} {u1} выпустил' . ($this->u->info['sex'] === 1 ? 'a' : '') . " зверя «{$animal['name']}».",
            ];
            Log::add($logData);

            Db::sql('update users set login = ?, obraz = ?, battle = ? where id = ?', [$animal['name'], $animal['obraz'] . '.gif', $btl->i->id, $b['id']]);
            Db::sql('update stats set team = ? where id = ?', [$this->u->info['team'], $b['id']]);
            Db::sql('update users_animal set eda = ? where id = ?', [$animal['eda'], $animal['id']]);
            $this->u->addAction(time(), 'animal_use' . $btl->i->id, $animal['level']);
        }
    }

    private function processPriem(int $id, Battle $btl): void
    {
        $target = '';
        $targetNotEmpty = false;
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $target = (string)filter_input(INPUT_POST, 'useon');
            $targetNotEmpty = $target && $target !== 'none';
        }
        $cup = false;
        $priemsOnPlayer = explode('|', $this->u->info['priems']);
        $pz = explode('|', $this->u->info['priems_z']);
        if ($priemsOnPlayer[$id] <= 0 || $pz[$id] > 0 || $this->u->info['hpNow'] < 1) {
            return;
        }

        $priem = Db::getRow('select * from priems where level <= ? and id = ?', [$this->u->info['level'], $priemsOnPlayer['id']]);

        if (isset($priem['id']) && $priem['activ'] != 1) {
            if ($priem['activ'] == 0) {
                unset($priem);
            } elseif ($priem['activ'] > 1) {
                //Книжный прием
                if ($this->testActiv($priem['activ']) == 0) {
                    unset($priem);
                }
            }
        }

        if (!isset($priem['id'])) {
            return;
        }

        $notr = 0;
        $priem['useon_user'] = $this->u->info['enemy'];
        if ($targetNotEmpty) {
            $this->ue = Db::getRow('select
             users.id, login, login2, online, admin, city, cityreg, align, clan, level, money, money3, money4, battle, sex, obraz, win, win_t, lose, lose_t, nich, 
             timeMain, invis, bot_id, animal, type_pers, notrhod, bot_room, inUser, inTurnir, inTurnirnew, stopexp, `real`, stats.* 
             from users inner join stats on users.id = stats.id where (login = ? or login2 = ?) and (inUser > 0 or (battle = ? and hpNow > 0))
                 order by users.id desc limit 1', [$target, $target, $btl->i->id]);

            if (isset($this->ue['id']) && $this->ue['inUser'] > 0) {
                $this->ue = Db::getRow('select
             users.id, login, login2, online, admin, city, cityreg, align, clan, level, money, money3, money4, battle, sex, obraz, win, win_t, lose, lose_t, nich, 
             timeMain, invis, bot_id, animal, type_pers, notrhod, bot_room, inUser, inTurnir, inTurnirnew, stopexp, `real`, stats.* 
             from users inner join stats on users.id = stats.id where battle = ? and hpNow > 0 and users.id = ?
                 order by users.id limit 1', [$btl->i->id, $this->ue['inUser']]);
            }

            if (!isset($this->ue['id']) && $priem['trUser'] > 0) {
                $notr++;
            }
            if ($priem['team'] == 1) {
                //свои
                if ($this->u->info['team'] != $this->ue['team']) {
                    $notr++;
                }
            } elseif ($priem['team'] == 2) {
                //противники
                if ($this->u->info['team'] == $this->ue['team']) {
                    $notr++;
                }
            }
        } else {
            $check = Db::getValue('select count(id) from battle_act where battle = ? and uid1 = ? and uid2 = ?', [$btl->i->id, $this->u->info['id'], $this->u->info['enemy']]) > 0;

            if (($this->u->info['enemy'] == 0 || $check) && ($priem['tr_hod'] > 0 || $priem['trUser'] > 0)) {
                $notr++;
            }
        }

        $notr += $this->testpriem($priem, 1, $this->ue['id']);

        if ($this->ue['id'] > 0) {
            $notr += $this->testRazmenOldUser($this->ue['id'], $this->u->info['enemy'], $priem['id']);
        }

        if ($notr != 0) {
            return;
        }

        Db::sql('update stats set last_pr = ? where id = ?', [$priem['id'], $this->u->info['id']]);

        //Приемы на персонажах
        $markuids = [];
        if ($this->ue['id'] > 0) {
            $btl->priemsRazmen([$this->u->info['id'], $this->ue['id']], 'fast');
            $markuids[] = $this->ue['id'];
        } else {
            $btl->priemsRazmen([$this->u->info['id'], $this->u->info['enemy']], 'fast');
            $markuids[] = $this->u->info['enemy'];
        }
        $markuids[] = $this->u->info['id'];

        Db::sql('update eff_users set mark = 1 where uid in (?)', [implode(',', $markuids)]);

        if (file_exists('../../_incl_data/class/Priem/' . $priem['id'] . '.php')) {
            $u = $this->u; // Для присоедиянемых файлов.
            require_once '../../_incl_data/class/Priem/' . $priem['id'] . '.php';
            $this->testDie($this->ue['id']);
        } else {
            echo 'useSkill' . $priem['id'];
        }

        if ($cup) { // Из подключаемых файлов.
            return;
        }

        $this->uppz($priem, $id);
        //Отнимаем тактики
        //$this->mintr($pl);
        if ($priem['tr_hod'] > 0) {
            $this->trhod($priem);
        }

        if ($priem['id'] != 258) {
            if ($priem['cancel_eff'] == '') {
                $priem['cancel_eff'] = '258';
            } else {
                $priem['cancel_eff'] .= ',258';
            }
        }

        if ($priem['cancel_eff'] == '') {
            return;
        }

        $i = 0;
        $e = explode(',', $priem['cancel_eff']);
        while ($i < count($e)) {
            if ($e[$i] <= 0) {
                $i++;
                continue;
            }

            if ($e[$i] == 258) {
                $uid = $this->u->info['id'];
            } else {
                $uid = $this->ue['id'];
            }

            $nem = Db::getRow('select * from eff_users where uid = ? and v1 = \'priem\' and v2 = ? and mark = 1 limit 1', [$uid, $e[$i]]);

            if (isset($nem['id'])) {
                $nem['priem'] = Db::getRow('select * from priems where id = ?', [$e['id']]);
                $btl->delPriem($nem, $btl->users[$btl->uids[$this->ue['id']]], 500);
            }

            $i++;
        }
    }

    private function testActiv($id)
    {
        $r = 0;
        if (
            $this->u->info['admin'] > 0 ||
            $this->u->info['nadmin'] > 0 ||
            $this->u->info['id'] > 0) {
            $r = 1;
        } else {
            $test = (bool)Db::getValue("select count(id) from actions where uid = ? and time < unix_timestamp() and vars = 'read' and vals = ?", [$this->u->info['id'], $id]);
            if ($test) {
                $r = 1;
            }
        }
        return $r;
    }

    private function testpriem($pl, $t = 1, $o = 0): int
    {
        global $btl;
        $tr = Conversion::dataStringToArray($pl['tr']);
        $d2 = Conversion::dataStringToArray($pl['date2']);
        $x = 1;
        $notr = 0;

        if ($t == 2 && $pl['id'] == 181) {
            $imun = mysql_fetch_assoc(
                mysql_query(
                    'SELECT * FROM `eff_users` WHERE `uid` = "' . $this->u->info['enemy'] . '" and `v2`="191" and `delete`="0" LIMIT 1'
                )
            );
            if ($imun) {
                $notr++;
            }
        }

        if (
            isset($btl->stats[$btl->uids[$this->u->info['id']]]['nousepriem']) &&
            $btl->stats[$btl->uids[$this->u->info['id']]]['nousepriem'] > 0 &&
            $pl['nosh'] == 0 &&
            ($btl->stats[$btl->uids[$this->u->info['id']]]['noshock_voda'] <= 0 || !str_starts_with($pl['img'], 'wis_water_'))
        ) {
            $notr++;
        }


        if (isset($btl->stats[$btl->uids[$this->u->info['id']]]['notuse_last_pr']) &&
            $pl['id'] == $btl->stats[$btl->uids[$this->u->info['id']]]['notuse_last_pr']) {
            $notr++;
        }

        while ($x <= 7) {
            if (isset($btl->uids[$this->u->info['id']], $btl->users[$btl->uids[$this->u->info['id']]])) {
                if ($btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] < $pl['tt' . $x] && $x != 7 && $pl['tt' . $x] > 0) {
                    $notr++;
                } elseif ($x == 7) {
                    if ($pl['tt' . $x] > 0 && $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] <= 0) {
                        $notr++;
                    }
                }
            }
            $x++;
        }


        if ($pl['xuse'] > 0) {
            $xu = ActionModel::testCount(["vars = use_priem_{$btl->i->id}_{$this->u->info['id']}", "vals = {$pl['id']}"], $pl['xuse']);
            if ($xu >= $pl['xuse']) {
                $notr++;
            }
        }

        $x = 0;
        while ($x < count($this->statnames->sysRequirementNames)) {
            $n = $this->statnames->sysRequirementNames[$x];
            if (isset($tr['tr_' . $n])) {
                if ($n == 'lvl') {
                    if ($tr['tr_' . $n] > $this->u->info['level']) {
                        $notr++;
                    }
                } elseif ($tr['tr_' . $n] > $this->u->stats[$n]) {
                    $notr++;
                }
            }
            $x++;
        }


        if ($pl['activ'] == 0 || ($this->testActiv($pl['activ']) == 0 && $pl['activ'] > 1)) {
            $notr++;
        }


        //if($t==2)
        //{
        if (isset($d2['onlyOne']) || isset($d2['onlyOneX1'])) {
            if (isset($d2['onlyOneX1'])) {
                if ($d2['onlyOneX1'] == 1) {
                    $pru = mysql_fetch_assoc(
                        mysql_query(
                            'SELECT * FROM `eff_users` WHERE `uid` = "' . $this->u->info['id'] . '" AND `v2` = "' . $pl['id'] . '" AND `delete` = "0" AND `x` >= 1 LIMIT 1'
                        )
                    );
                    if (isset($pru['id']) && $pru['x'] >= $d2['onlyOne']) {
                        $notr++;
                    }
                }
            } elseif (isset($d2['onlyOne'])) {
                if ($d2['onlyOne'] > 1) {
                    $pru = mysql_fetch_assoc(
                        mysql_query(
                            'SELECT * FROM `eff_users` WHERE `uid` = "' . $this->u->info['id'] . '" AND `v2` = "' . $pl['id'] . '" AND `delete` = "0" AND `x` > 1 LIMIT 1'
                        )
                    );
                    if (isset($pru['id']) && $pru['x'] >= $d2['onlyOne']) {
                        $notr++;
                    }
                }
            }
        }

        //Требует чтобы не было
        if (isset($tr['tr_nousepriem'])) {
            $x = 0;
            $nouse = explode(',', $tr['tr_nousepriem']);
            while ($x < count($nouse)) {
                $nousev = explode('.', $nouse[$x]);
                if (isset($btl->stats[$btl->uids[$this->u->info['id']]]['prsu'][$nousev[0]]) && $btl->stats[$btl->uids[$this->u->info['id']]]['prsu'][$nousev[0]] >= 0) {
                    if ($nousev[2] > 1) {
                        if ($nousev[2] <= $btl->stats[$btl->uids[$this->u->info['id']]]['prsu'][$nousev[0]]) {
                            $notr++;
                        }
                    } else {
                        $notr++;
                    }
                }
                $x++;
            }
            unset($nouse, $nousev);
        }

        if (isset($tr['tr_type_itm1'])) {
            //требует наличие предмета определенного типа
            $itmt = mysql_fetch_assoc(
                mysql_query(
                    'SELECT `u`.`id` FROM `items_users` AS `u` LEFT JOIN `items_main` AS `m` ON `m`.`id` = `u`.`item_id` WHERE `m`.`type` = "' . $tr['tr_type_itm1'] . '" AND `u`.`inOdet` > 0 AND `u`.`uid` = "' . $this->u->info['id'] . '" AND `u`.`delete` = "0" LIMIT 1'
                )
            );
            if (!isset($itmt['id'])) {
                $notr++;
            }
        }

        if (isset($tr['tr_mpNow'])) {
            if (isset($btl->stats[$btl->uids[$this->u->info['id']]])) {
                if ($btl->stats[$btl->uids[$this->u->info['id']]]['mpNow'] < round(
                        $tr['tr_mpNow'] / 100 * (100 - $btl->stats[$btl->uids[$this->u->info['id']]]['min_use_mp'])
                    )) {
                    $notr++;
                }
            } elseif ($this->u->info['mpNow'] < $tr['tr_mpNow']) {
                $notr++;
            }
        }

        if (isset($btl->uids[$this->u->info['id']], $btl->stats[$btl->uids[$this->u->info['id']]])) {
            if ($pl['trUser'] == 1) {
                //требует чтобы пользователь с кем-то разменивался (при ожидании прием гаснит)
                if (isset($btl->ga[$this->u->info['id']][$this->u->info['enemy']])) {
                    $notr++;
                }
            } elseif ($pl['trUser'] == 2 && $o > 0) {
                //требует чтобы пользователь с кем-то разменивался (при ожидании не пропадает, но не используется)
                $ga = mysql_fetch_assoc(
                    mysql_query(
                        'SELECT * FROM `battle_act` WHERE `battle` = "' . $btl->i->id . '" AND `uid1` = "' . $this->u->info['id'] . '" AND `uid2` = "' . $btl->users[$btl->uids[$this->u->info['id']]]['enemy'] . '" LIMIT 1'
                    )
                );
                if (isset($ga['id'])) {
                    $notr++;
                }
            }
        }

        return $notr;
    }

    private function testRazmenOldUser($u2, $u1, $plid)
    {
        global $btl, $u;
        $r = 0;
        //Уровень -противника- ниже уровня -цели-
        if ($btl->users[$btl->uids[$u2]]['id'] != $this->u->info['id']) {
            if ($btl->users[$btl->uids[$u1]]['level'] < $btl->users[$btl->uids[$u2]]['level']) {
                $r = 1;
                echo '<div style="color: red; font-weight: bold; text-align: center;">Нельзя кастовать через слабого противника в сильного</div>';
            } elseif ($btl->users[$btl->uids[$u1]]['bot'] > 0 && $btl->users[$btl->uids[$u2]]['bot'] == 0) {
                echo '<div style="color: red; font-weight: bold; text-align: center;">Нельзя кастовать через монстров или зверя</div>';
                $r = 1;
            } elseif (
                $btl->users[$btl->uids[$u1]]['id'] != $btl->users[$btl->uids[$u2]]['id'] &&
                !in_array($plid, [35, 63, 64, 65, 66, 85, 86, 87, 88, 89, 90, 104, 105, 106, 107, 134, 135, 136, 137])
            ) //Атака в темную 90,89,88,87,86,85,35
            {
                $this->addPriem(
                    $this->u->info['id'], '344', 'add_m11=-' . round($this->u->stats['m11'] * 75 / 100), 1, 77, 1,
                    $this->u->stats['id'], 3, 'тьма', 0, 0, 1
                ); //ТУТ понижение урона при уроне через персонажа
            }
        }
        return $r;
    }

    /**
     * @param int $uid на кого кастуем
     * @param int $pr id приема
     * @param int|string $data дата, если -1, то добавляем дату3
     * @param int $d2
     * @param            $tm
     * @param int $h ход
     * @param int $uu id юзера который использовал
     * @param            $max
     * @param            $bj
     * @param            $tp
     * @param            $ch
     * @param            $rdt
     * @param            $tr_life_user
     * @param            $noupdatebtl
     * @param            $noplus
     * @param            $pname
     * @return bool
     */
    public function addPriem(
        $uid,
        $pr,
        $data,
        $d2,
        $tm,
        $h,
        $uu,
        $max,
        $bj,
        $tp = 0,
        $ch = 0,
        $rdt = 0,
        $tr_life_user = 0,
        $noupdatebtl = 0,
        $noplus = 0,
        $pname = null
    )
    {
        global $btl;
        //$pl = mysql_fetch_assoc(mysql_query('SELECT * FROM `priems` WHERE `id` = ' . (int)$pr));
        $pl = Db::getRow('select * from priems where id = ?', [$pr]);

        $r = false;

        if (!$pl['id']) {
            return false;
        }

        if ($data == -1) {
            $data = $this->redate($pl['date3'], $this->u->info['id']);
        } elseif ($d2 == 1) {
            $data .= '|' . $this->redate($pl['date3'], $this->u->info['id']);
        }

        $this->cancelEffects($pl['cancel_eff2'], $uid, $btl);

        if ($max <= 0) {
            return false;
        }

        if ($noplus == 0) {
            if ($pl['zmu'] == 1) {
                $num = Db::getRow(
                    'select * from eff_users where bj = ? and user_use = ? and uid = ? and `delete` = 0',
                    [$bj, $this->u->info['id'], $uid]
                );
            } else {
                $num = Db::getRow(
                    'select * from eff_users where bj = ? and uid = ? and `delete` = 0',
                    [$bj, $uid]
                );
            }
        }

        if (isset($num['id']) && ($num['user_use'] != $this->u->info['id'] && $pl['zmu'] != 2)) {
            // удаляем эффект
            Effects::removeById(0, $num['id']);

            $i = 0;
            while ($i < count($btl->stats[$btl->uids[$uid]]['effects'])) {
                if ($btl->stats[$btl->uids[$uid]]['effects'][$i]['id'] == $num['id']) {
                    //обновляем
                    $btl->stats[$btl->uids[$uid]]['effects'][$i]['delete'] = time();
                }
                $i++;
            }
            unset($num);
        }
        if (!isset($num['id'])) {
            $image = !empty($pl['img']) ? $pl['img'] : $pl['id'];
            $name = !empty($pname) ? $pname : $pl['name'];
            $image .= '.gif';

            Effects::addCustom(
                [
                    'id_eff' => 22,
                    'uid' => $uid,
                    'name' => $name,
                    'data' => $data,
                    'timeUse' => $tm,
                    'user_use' => $uu,
                    'v1' => 'priem',
                    'v2' => $pl['id'],
                    'img2' => $image,
                    'hod' => $h,
                    'bj' => $bj,
                    'tr_life_user' => floor($tr_life_user),
                ]
            );

            $r = true;

            /* добавляем данные к $btl->eff */
            if ($noupdatebtl == 0) {
                $btl->stats[$btl->uids[$uid]] = $this->u->getStats($uid, 0);
            }
        } elseif ($num['x'] < $max) {
            //Добавляем еще и обновляем заряды
            $num['x']++;
            $num['hod'] = $h;
            if ($data != -1 && $data != '' && $d2 == 2) {
                $num['data'] .= '|' . $data;
                Effects::setHod($num['id'], $h, 'x + 1', $num['data']);
            } else {
                Effects::setHod($num['id'], $h, 'x + 1');
            }
            $r = true;
        } else {
            //обновляем заряды
            $num['hod'] = $h;
            if ($data != -1 && $data != '' && $d2 == 2) {
                $num['data'] .= '|' . $data;
                Effects::setHod($num['id'], $h, data: $num['data']);
            } else {
                Effects::setHod($num['id'], $h);
            }
            $r = true;
        }

        if (isset($num['id'])) {
            foreach ($btl->stats[$btl->uids[$uid]]['effects'] as $effect) {
                if ($effect['id'] != $num['id']) {
                    continue;
                }
                $effect['data'] = $num['data'];
                $effect['hod'] = $num['hod'];
                $effect['x'] = $num['x'];
            }
        }

        return $r;
    }

    /** Получает строку data c шаблонной записью типа add_m11=2*{lvl1} и конвертирует в реальную строку.
     * <br>Шаблон: <br>lvl1 = $uid[level] <br>ts5 = $uid[s5] <br>mpAll = $uid[mpAll]
     * @param string $pl строка в формате data
     * @param int $uid пользователь, параметры которого используются для подставки в шаблон.
     * @return string строка в формате data с развёрнутыми шаблонами.
     */
    public function redate($pl, $uid)
    {
        global $btl;
        $i = 0;
        if ($pl != '') {
            $e = explode('|', $pl);
            while ($i < count($e)) {
                $f = explode('=', $e[$i]);
                //                $f[1] = $this->getdr(
                //                    $f[1], [0 => 'lvl1', 1 => 'ts5', 2 => 'mpAll'], [
                //                    0 => $btl->users[$btl->uids[$uid]]['level'],
                //                    1 => $btl->stats[$btl->uids[$uid]]['s5'],
                //                    2 => $btl->stats[$btl->uids[$uid]]['mpAll'],
                //                ]
                //                );
                $f[1] = $this->getDynamicInfo($f[1]);
                if ($f[0] != '' && $f[1] != '') {
                    $e[$i] = implode('=', $f);
                }
                $i++;
            }
            $pl = implode('|', $e);
        }
        return $pl;
    }

    /**
     * @param $match
     * @return false|float
     */
    private function getDynamicInfo($match)
    {
        $tmpl = [
            'lvl1' => $this->u->info['level'],
            'ts5' => $this->u->stats['s5'],
            'mpAll' => $this->u->stats['mpAll'],
        ];
        foreach ($tmpl as $k => $v) {
            $match = str_ireplace('{' . $k . '}', $v, $match);
        }
        $p = $match[2];

        if (preg_match('/(\d+)(?:\s*)([+\-*\/])(?:\s*)(\d+)/', $match[2], $matches) !== false) {
            $operator = $matches[2];

            switch ($operator) {
                case '+':
                    $p = $matches[1] + $matches[3];
                    break;
                case '-':
                    $p = $matches[1] - $matches[3];
                    break;
                case '*':
                    $p = $matches[1] * $matches[3];
                    break;
                case '/':
                    $p = $matches[1] / $matches[3];
                    break;
                default:
            }
        }
        return floor($p);
    }

    private function cancelEffects($effects_ids, $uid, Battle $btl)
    {
        $arr = explode(',', $effects_ids);
        if (!is_array($arr) || empty($arr)) {
            return;
        }
        foreach ($arr as $eid) {
            if ($eid <= 0) {
                continue;
            }
            $p = Db::getRow(
                'select * from eff_users where uid = ? and v1 = ? and v2 = ? and `delete` = 0', [$uid, 'priem', $eid]
            );
            if (!$p['id']) {
                continue;
            }
            $p['priem'] = Db::getRow('select * from priems where id = ?', [$eid]);
            $btl->delPriem($p, $btl->users[$btl->uids[$uid]], 2);
        }
    }

    public function testDie($u1)
    {
        global $btl;
        //Персонаж 1 погиб от рук персонаж 2
        $btl->spaCheck($btl->stats[$btl->uids[$u1]]['id']);
    }

    public function uppz($pl, $id)
    {
        global $u, $btl;
        $this->actpridMax($pl);
        $p = explode('|', $this->u->info['priems']);
        $pz = explode('|', $this->u->info['priems_z']);
        $pz[(int)$id] = $pl['zad'];
        $i = 0;
        $pe = explode(',', $pl['actprid']);
        $piz = [];
        while ($i < count($pe)) {
            $piz[$pe[$i]] = 1;
            $i++;
        }
        $i = 0;
        $pe = explode(',', $pl['actprid_one']);
        $piz2 = [];
        while ($i < count($pe)) {
            $piz2[$pe[$i]] = 1;
            $i++;
        }
        $i = 0;
        while ($i < count($p)) {
            if ($p[$i] > 0) {
                if (isset($piz[$p[$i]])) {
                    if ($pl['id'] == 281) {
                        //Жертва воде + воздуху дает 5 ед. задержки на землю и огонь
                        if ($p[$i] == 246 || $p[$i] == 186) {
                            $pz[$i] = 5;
                        } else {
                            $pz[$i] = $pl['zad'];
                        }
                    } else {
                        $pz[$i] = $pl['zad'];
                    }
                }
                if (isset($piz2[$p[$i]]) && $pz[$i] == 0) {
                    $pz[$i] = 1;
                }
            }
            $i++;
        }
        $pz = implode('|', $pz);
        $this->u->info['priems_z'] = $pz;
        $btl->users[$btl->uids[$this->u->info['id']]]['priems_z'] = $pz;
        $btl->stats[$btl->uids[$this->u->info['id']]]['priems_z'] = $pz;
        $tr = Conversion::dataStringToArray($pl['tr']);
        if (isset($tr['tr_mpNow'])) {
            $tr['tr_mpNow'] = round($tr['tr_mpNow'] / 100 * (100 - $this->u->stats['min_use_mp']));
            $btl->users[$btl->uids[$this->u->info['id']]]['mpNow'] -= $tr['tr_mpNow'];
            $btl->stats[$btl->uids[$this->u->info['id']]]['mpNow'] -= $tr['tr_mpNow'];
            if ($btl->stats[$btl->uids[$this->u->info['id']]]['mpNow'] < $btl->users[$btl->uids[$this->u->info['id']]]['mpNow']) {
                $btl->users[$btl->uids[$this->u->info['id']]]['mpNow'] = $btl->stats[$btl->uids[$this->u->info['id']]]['mpNow'];
            }
        }
        $this->u->info['mpNow'] = $btl->users[$btl->uids[$this->u->info['id']]]['mpNow'];
        mysql_query(
            'UPDATE `stats` SET `mpNow` = "' . $this->u->info['mpNow'] . '",`priems_z` = "' . $pz . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
        );
    }

    private function actpridMax($pl)
    {
        global $u, $btl;
        if ($pl['actprid2'] > 0 || $pl['actprid3'] > 0) {
            $i = 0;
            $pe = explode('|', $this->u->info['priems']);
            $piz = [];
            while ($i < count($pe)) {
                if ($pl['sbr'] == 0) {
                    //все блокируем
                    $psp = mysql_fetch_assoc(
                        mysql_query('SELECT * FROM `priems` WHERE `id` = "' . ((int)$pe[$i]) . '" LIMIT 1')
                    );
                } else {
                    //Только текущую школу магии
                    $imgnm = '';
                    $nm = explode('_', $pl['img']);
                    if ($nm[0] == 'wis') { //магия
                        $imgnm = $nm[0] . '_' . $nm[1] . '%';
                    } else {
                        $imgnm = $nm[0] . '%';
                    }
                    //только данной школы
                    $psp = mysql_fetch_assoc(
                        mysql_query(
                            'SELECT * FROM `priems` WHERE `id` = "' . ((int)$pe[$i]) . '" AND `img` LIKE "' . $imgnm . '" LIMIT 1'
                        )
                    );
                }
                if ($pl['noprid'] == 0 && isset($psp['id']) && $psp['tr_hod'] == 0 && $psp['type_pr'] == 1 && $psp['noprid'] == 0) {
                    if ($pl['actprid2'] > 0) {
                        $piz[$pe[$i]] = (int)$pl['actprid2'];
                    } elseif ($pl['actprid3'] > 0) {
                        $piz[$pe[$i]] = $psp['zad'];
                    }
                }
                $i++;
            }
            $pz = explode('|', $this->u->info['priems_z']);
            $p = explode('|', $this->u->info['priems']);
            $i = 0;
            while ($i < count($p)) {
                if ($p[$i] > 0 && isset($piz[$p[$i]]) && $pz[$i] == 0) {
                    $pz[$i] = $piz[$p[$i]];
                }
                $i++;
            }
            $pz = implode('|', $pz);
            $this->u->info['priems_z'] = $pz;
            $btl->users[$btl->uids[$this->u->info['id']]]['priems_z'] = $pz;
            $btl->stats[$btl->uids[$this->u->info['id']]]['priems_z'] = $pz;
        }
    }

    private function trhod($pl)
    {
        global $u, $btl;
        if ($this->u->info['notrhod'] == -1) {
            $this->u->info['notrhod'] = 0;
            if ($this->u->stats['magic_cast'] > 0) {
                $this->u->info['notrhod'] = $this->u->stats['magic_cast'];
            }
            mysql_query(
                'UPDATE `users` SET `notrhod` = "' . $this->u->info['notrhod'] . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
            );
        }
        if ($this->u->info['notrhod'] > 0) {
            if ($pl['tr_hod'] > 0) {
                $this->u->info['notrhod']--;
                mysql_query(
                    'UPDATE `users` SET `notrhod` = "' . $this->u->info['notrhod'] . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
                );
            }
        } else {
            $a1 = mysql_fetch_assoc(
                mysql_query(
                    'SELECT * FROM `battle_act` WHERE `battle` = "' . $btl->i->id . '" AND `uid2` = "' . $this->u->info['id'] . '" AND `uid1` = "' . $this->u->info['enemy'] . '" LIMIT 1'
                )
            );
            if (isset($a1['id'])) {
                //противник ударил, пишем что игрок 2 пропустил ход
                mysql_query(
                    'UPDATE `battle_act` SET `out2` = "1",`tpo2` = "2" WHERE `id` = "' . $a1['id'] . '" LIMIT 1'
                );
                $a1['out2'] = 1;
                $a1['tpo2'] = 2;
                $btl->atacks[$a1['id']] = $a1;
                $btl->users[$this->u->info['id']]['priems_z'] = $this->u->info['priems_z'];
                $btl->startAtack($a1['id']);
            } else {
                //бьем противника с пропуском хода
                mysql_query(
                    'INSERT INTO `battle_act` (`battle`,`uid1`,`uid2`,`time`,`out1`,`type`,`tpo1`) VALUES ("' . $btl->i->id . '","' . $this->u->info['id'] . '","' . $this->u->info['enemy'] . '","' . time() . '","1","1","2")'
                );
            }
        }
    }

    public function plusData($d1, $d2)
    {
        global $u;
        $j1 = Conversion::dataStringToArray($d1);
        $j2 = Conversion::dataStringToArray($this->redate($d2, $this->u->info['id']));
        $v = $this->u->lookKeys($this->redate($d2, $this->u->info['id']), 0); // ключи 2
        //добавляем данные друг к другу
        $i = 0;
        $inf = '';
        while ($i < count($v)) {
            $j1[$v[$i]] += $j2[$v[$i]];
            $vi = str_replace('add_', '', $v[$i]);
            if ($this->u->is[$vi] != '') {
                if ($j2[$v[$i]] > 0) {
                    $inf .= $this->u->is[$vi] . ': +' . ($j2[$v[$i]] * (1 + $mpr['x'])) . ', ';
                } elseif ($j2[$v[$i]] < 0) {
                    $inf .= $this->u->is[$vi] . ': ' . ($j2[$v[$i]] * (1 + $mpr['x'])) . ', ';
                }
            }
            $i++;
        }
        $inf = rtrim($inf, ', ');
        $j1 = Conversion::arrayToDataString($j1);
        return $j1;
    }

    public function maxtr($x, $val)
    {
        global $u, $btl;
        $this->u->info['tactic' . $x] += $val;
        $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] += $val;
        if ($this->u->info['tactic' . $x] < 0) {
            $this->u->info['tactic' . $x] = 0;
        }
        if ($btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] < 0) {
            $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] = 0;
        }
        $rt = '`tactic' . $x . '`="' . $this->u->info['tactic' . $x] . '"';
        mysql_query('UPDATE `stats` SET ' . $rt . ' WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1');
    }

    public function reuns($id)
    {
        global $u, $c, $code;
        $p = explode('|', $this->u->info['priems']);
        if ($p[(int)$id] > 0) {
            //снимаем прием
            $p[(int)$id] = 0;
            $p = implode('|', $p);
            mysql_query(
                'UPDATE `stats` SET `priems` = "' . mysql_real_escape_string(
                    $p
                ) . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
            );
            $this->u->info['priems'] = $p;
        }
    }

    //выводим приемы $id - 1 (вне боя), 2 - в бою

    /** Одеть приём в слот?
     * @param $id
     * @return void
     */
    public function uns($id)
    {
        global $u, $c, $code;

        $pl = $this->getTechniquesInfo($id);

        if (!isset($pl['id']) || $this->testpriem($pl, 1) != 0) {
            return;
        }
        $yes = -1;
        $non = -1;
        $i = 0;
        $p = explode('|', $this->u->info['priems']);
        while ($i < $this->u->info['priemslot']) {
            if ($non == -1 && $p[$i] == 0) {
                $non = $i;
            }
            if ($p[$i] == $pl['id']) {
                $yes = $i;
            }
            $i++;
        }

        if ($yes != -1) {
            //такой прием уже стоит, ничего не делаем
            return;
        }
        if ($non != -1) {
            //одеваем прием
            $p[$non] = $pl['id'];
            $p = implode('|', $p);
            $upd = mysql_query(
                'UPDATE `stats` SET `priems` = "' . $p . '" WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1'
            );
            if ($upd) {
                TrainingManager::getInstance()
                    ->addPoint(
                        'my_user_fourth_quest', function (TrainingManager $manager) {
                        $manager->store();
                    }
                    );
                $this->u->info['priems'] = $p;
            }
        } else {
            //снимаем последний прием
            echo 'Снимаем последний прием...';
        }
    }

    public function getTechniquesInfo(?int $id = null): array
    {
        if (isset($id)) {
            return Db::getRow('select * from priems where level <= ? and activ > 0 and id = ? order by img,level', [$this->u->info['level'], $id]);
        }

        return Db::getRows('select * from priems where level <= ? and activ > 0 order by img,level', [$this->u->info['level']]);
    }

    public function seeMyPriems(): void
    {
        $i = 0;
        $p = explode('|', $this->u->info['priems']);
        $pr = '';
        $all = (int)$_GET['all'];
        while ($i < $this->u->info['priemslot']) {
            if ($p[$i] > 0) {
                $pl = Db::getRow('select * from priems where level <= ? and activ > 0 and id = ?', [$this->u->info['level'], $p[$i]]);
                $lvar = $this->priemInfo($pl, $i);
                $lvar = $lvar[0];

                if (isset($_GET['inv'])) {
                    $cl = "location.href='/main.php?all=$all&skills=1&rz=4&p_raz=all'";
                } else {
                    $cl = "location.href='/main.php?all=$all&skills=1&unuse_priem=$i&rz=4&p_raz=' + p_raz";
                }
                $cl = 'onclick="' . $cl . '"';

                $cli2 = '';
                if ((isset($this->u->stats['nopriems']) && $pl['nosh'] == 0) || isset($this->u->stats['notuse_last_pr']) && $this->u->stats['notuse_last_pr'] == $pl['id']) {
                    $cli2 = ' class="nopriemuse" ';
                }
                /// ТУТ!
                $priemName = $pl['name'];
                $priemImg = $pl['img'];
                $pr .= <<<HTML
                <a onmouseover="let a = `<b>$priemName</b><br>$lvar`; top.hi(this,a,event,3,0,1,1,'width: 240px;')" onmouseout="top.hic();" onmousedown="top.hic();" href="javascript:void(0)" $cl>
                    <img $cli2 style="margin-top: 3px; margin-left: 4px;" src="//img.new-combats.tech/i/eff/$priemImg.gif" alt=""></a>
                </a>
                HTML;

            } elseif (isset($_GET['inv'])) {
                $pr .= <<<HTML
                    <a title="Перейти к настройкам приемов" href="javascript:void(0)" onclick="location.href='/main.php?all=$all&skills=1&rz=4&p_raz=all'">
                        <img style="margin-top:4px; margin-left:4px;" src="//img.new-combats.tech/i/items/w/clearPriem.gif" alt="">
                    </a>
                HTML;

            } else {
                $pr .= '<img style="margin-top:4px; margin-left:4px;" src="//img.new-combats.tech/i/items/w/clearPriem.gif" alt="">';
            }
            $i++;
        }

        echo '<div>' . $pr . '</div>';
    }

    /**
     * Летит в js, двойные кавычки не использовать.
     * @param array $pl
     * @param int $id
     * @return array
     */
    private function priemInfo(array $pl, int $id = -1): array
    {
        global $btl;
        $pz = explode('|', $this->u->info['priems_z']);
        $tr = Conversion::dataStringToArray($pl['tr']);
        $trs = '';
        $x = 0;

        while ($x < count($this->statnames->sysRequirementNames)) {
            $n = $this->statnames->sysRequirementNames[$x];
            if (isset($tr['tr_' . $n])) {
                if ($tr['tr_' . $n] > $this->u->stats[$n]) {
                    $trs .= "<span style='color: red;'>";
                }
                $trs .= '<br>• ';
                $trs .= $this->statnames->requirementNames[$n] . ': ' . $tr['tr_' . $n];
                if ($tr['tr_' . $n] > $this->u->stats[$n]) {
                    $trs .= '</span>';
                }
            }
            $x++;
        }

        $lvar = '';
        $j = 1;
        $nm = [1 => 'hit', 2 => 'krit', 3 => 'counter', 4 => 'block', 5 => 'parry', 6 => 'hp', 7 => 'spirit'];
        while ($j <= 6) {
            if ($pl['tt' . $j] > 0) {
                $lvar .= '<img src=//img.new-combats.tech/i/micro/' . $nm[$j] . '.gif> ' . round($pl['tt' . $j], 2) . ' &nbsp; ';
            }
            $j++;
        }
        if ($pl['tt7'] > 0) {
            if ($lvar != '') {
                $lvar .= '<br>';
            }
            $lvar .= 'Сила духа: ' . round($pl['tt' . $j], 2) . '<br>';
        }
        $lvar .= '<br>';
        if ($pl['zad'] > 0) {
            $lvar .= 'Задержка: ' . $pl['zad'];
            if ($pz[$id] > 0) {
                $lvar .= ' (еще ' . $pz[$id] . ')';
            }
            $lvar .= '<br>';
        }
        if (isset($tr['tr_mpNow']) && $tr['tr_mpNow'] > 0) {
            $tr['tr_mpNow'] -= round($tr['tr_mpNow'] / 100 * $this->u->stats['min_use_mp']);
            if ($this->u->info['mpNow'] < $tr['tr_mpNow'] || (isset($btl->stats[$btl->uids[$this->u->info['id']]]) && $btl->stats[$btl->uids[$this->u->info['id']]]['mpNow'] < $tr['tr_mpNow'])) {
                $lvar .= '<span style="color: red;">• Расход маны: ' . $tr['tr_mpNow'] . '</span><br>';
            } else {
                $lvar .= '• Расход маны: ' . $tr['tr_mpNow'] . '<br>';
            }
        }
        if ($pl['tr_hod'] > 0) {
            $lvar .= '• Прием тратит ход<br>';
        }
        if ($trs != '') {
            $lvar .= '<b>Требования:</b>' . $trs . '<br><br>';
        } else {
            $lvar .= '<br>';
        }

        $pl['info'] = preg_replace_callback("!(#)(.*?)(#)!is", [$this, 'getDynamicInfo'], $pl['info']);
        $lvar .= $pl['info'];
        return [0 => $lvar, 1 => $pz];
    }

    //Мощность / подавление / сопротивление и т.д.

    /**
     * Генерирует html строку для вставки в JS $("#priems").html(" сюда ");
     * @return string
     */
    public function seeMy(): string
    {
        global $btl;
        $i = 0;
        $p = explode('|', $this->u->info['priems']);
        $pr = '';
        $all = $_GET['all'] ??= '0';
        while ($i < $this->u->info['priemslot']) {
            if ($p[$i] > 0) {
                $pl = Db::getRow('select * from priems where level <= ? and activ > 0 and id = ?', [$this->u->info['level'], $p[$i]]);
                $cl = '';
                $lvar = $this->priemInfo($pl, $i);
                $pz = $lvar[1];
                $lvar = $lvar[0];

                if ($pl['type'] == 1) {
                    //моментально
                    if ($pl['onUser'] == 1) {
                        if ($pl['team'] == 1) {
                            if ($this->u->info['login2'] != '') {
                                $oninuser = $this->u->info['login2'];
                            } else {
                                $oninuser = $this->u->info['login'];
                            }
                        } else {
                            if ($btl->users[$btl->uids[$this->u->info['enemy']]]['login2'] != '') {
                                $oninuser = $btl->users[$btl->uids[$this->u->info['enemy']]]['login2'];
                            } else {
                                $oninuser = $btl->users[$btl->uids[$this->u->info['enemy']]]['login'];
                            }
                        }
                        $cl = 'href="javascript:void(0);" onClick="top.priemOnUser(' . $i . ',1,\'' . $pl['name'] . '\',\'' . $oninuser . '\',\'' . $pl['img'] . '\');"';
                        unset($oninuser);
                    } else {
                        $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ');"';
                    }
                } elseif ($pl['type'] == 2) {
                    //длительное
                    $cl = 'href="javascript:void(0);" onClick="usepriem(' . $i . ');"';
                } elseif ($pl['type'] == 3) {
                    $cl = 'href="javascript:void(0);" onClick="alert(\'Возможно используем?\');"';
                }

                $notr = $this->testpriem($pl, 2);

                $cli2 = '';
                if (($pz[$i] > 0 || $notr > 0) || (isset($this->u->stats['nopriems']) && $pl['nosh'] == 0) || isset($this->u->stats['notuse_last_pr']) && $this->u->stats['notuse_last_pr'] == $pl['id']) {
                    $cli2 = ' class="nopriemuse" ';
                }
                /// ТУТ!
                $priemName = $pl['name'];
                $priemImg = $pl['img'];

                // Слава StackOverflow! https://stackoverflow.com/a/43631576
                $var = json_encode("<b>$priemName</b><br>$lvar");
                $jsOnmouseover = "top.hi(this,$var,event,3,0,1,1,'width: 240px;')";
                $htmlJs = htmlspecialchars($jsOnmouseover, ENT_QUOTES);

                $pr .= <<<HTML
                <a onmouseover="$htmlJs" onmouseout="top.hic();" onmousedown="top.hic();" $cl>
                    <img $cli2 style="margin-top: 3px; margin-left: 4px;" src="//img.new-combats.tech/i/eff/$priemImg.gif" alt=""></a>
                </a>
                HTML;

            } else {

                if (isset($_GET['inv'])) {
                    $pr .= '<a title="Перейти к настройкам приемов" href="javascript:void(0)" onclick="location.href=\'main.php?all=' . $all . '&skills=1&rz=4&p_raz=all\'"><img style="margin-top:4px; margin-left:4px;" src="//img.new-combats.tech/i/items/w/clearPriem.gif" alt=""></a>';
                } else {
                    $pr .= '<img style="margin-top:4px; margin-left:4px;" src="//img.new-combats.tech/i/items/w/clearPriem.gif" alt="">';
                }

            }
            $i++;
        }
        if ($this->u->info['animal'] > 0) {
            $use_lst = (bool)ActionModel::testCount(["uid = {$this->u->info['id']}", "vars = animal_use{$btl->i->id}"]);
            if (!$use_lst) {
                $pr .= '<a onMouseOver="top.hi(this,\'<b>Выпустить зверя</b><Br>Ваш зверь вмешивается в поединок. Можно применять один раз за бой.\',event,3,0,1,1,\'width:240px\');" onMouseOut="top.hic();" onMouseDown="top.hic();" href="javascript:void(0);" onClick="usepriem(100500);"><img style="margin-top:1px; margin-left:3px;" src="//img.new-combats.tech/i/eff/pet_unleash.gif" width="40" height="25" /></a>';
            } else {
                $pr .= '<img onMouseOver="top.hi(this,\'<b>Выпустить зверя</b><Br>Ваш зверь вмешивается в поединок. Можно применять один раз за бой.\',event,3,0,1,1,\'width:240px\');" onMouseOut="top.hic();" onMouseDown="top.hic();" style="margin-top:1px; margin-left:2px;" class="nopriemuse" src="//img.new-combats.tech/i/eff/pet_unleash.gif" width="40" height="25" />';
            }
        }

        return str_replace('"', '\\"', $pr);
    }

    public function getByCategory(?int $category_id = null)
    {

        $priems = $this->getTechniquesInfo();

        $cl = '';

        foreach ($priems as $priem) {

            if ($this->pyes($priem['id']) || $this->testpriem($priem, 1) > 0) {
                $cl = 'filter: alpha(opacity=35); -moz-opacity: 0.35; -khtml-opacity: 0.35; opacity: 0.35;';
            }

            echo
            <<< HTML
                    <a href="javascript:void(0)" onclick="location.href='main.php?skills=1&rz=4&use_priem=$priem[id]';">
                        <img class="pwq$priem[category_id] pwqall" onMouseOver="top.popup(this, '(#$priem[id]) <b>$priem[name]</b><Br>{$this->priemInfo(
                $priem
            )[0]}');" onMouseOut="top.hic();" onMouseDown="top.hic();" style="display:none;margin-top:2px; $cl margin-left:1px;" src="//img.new-combats.tech/i/eff/$priem[img].gif" width="40" height="25" />
                    </a>
            HTML;
        }

    }

    private function pyes($id)
    {
        global $u;
        $p = explode('|', $this->u->info['priems']);
        $r = false;
        $i = 0;
        while ($i < count($p)) {
            if ($p[$i] == $id) {
                $r = true;
            }
            $i++;
        }
        return $r;
    }

    public function devouringFlame($id, $uid, $j_id, Battle $btl)
    {
        $a = 0;
        $u1 = 0;
        $u2 = 0;
        //
        $uid1 = $btl->atacks[$id]['uid1'];
        $uid2 = $btl->atacks[$id]['uid2'];
        if ($uid == $uid1) {
            $a = 1;
            $u1 = $uid1;
            $u2 = $uid2;
        } elseif ($uid == $uid2) {
            $a = 2;
            $u1 = $uid2;
            $u2 = $uid1;
        }
        if ($a <= 0) {
            return;
        }//Проверяем эффект
        $prv['j_priem'] = $btl->stats[$btl->uids[$u1]]['u_priem'][$j_id][0];

        $pvr['data'] = Conversion::dataStringToArray($btl->stats[$btl->uids[$u1]]['effects'][$prv['j_priem']]['data']);
        $pName = $btl->stats[$btl->uids[$u1]]['effects'][$prv['j_priem']]['name'];

        $pvr['hp'] = $pvr['data']['atgm'];

        $pvr['hpNow'] = floor($btl->stats[$btl->uids[$u1]]['hpNow']);
        $pvr['hpAll'] = $btl->stats[$btl->uids[$u1]]['hpAll'];

        //Используем проверку на урон приемов
        $pvr['hp'] = $btl->testYronPriem(
            $btl->stats[$btl->uids[$u1]]['effects'][$prv['j_priem']]['user_use'], $u1, 12, $pvr['hp'], 7, true, false, 1
        );

        $pvr['hpNow'] -= $pvr['hp'];
        $btl->priemYronSave($btl->stats[$btl->uids[$u1]]['effects'][$prv['j_priem']]['user_use'], $u1, $pvr['hp'], 0);

        $pvr['hpNow'] = $this->zeromax($pvr['hpNow'], $pvr['hpAll']);

        $btl->stats[$btl->uids[$u1]]['hpNow'] = $pvr['hpNow'];

        Db::sql('update stats set hpnow = ? where id = ?', [$btl->stats[$btl->uids[$u1]]['hpNow'], $u1]);

        $color = $this->logColor[self::FIRE];
        $prv['text'] = '{u2} утратил здоровье от &quot;{pr}&quot; ';
        if ($pvr['promah_type'] == 2) {
            $pvr['hp'] = '-';
        }
        $prv['text'] .= sprintf(
            "<b style='color: %s'>%s</b> [%d/%d]", $color, -$pvr['hp'], $pvr['hpNow'], $pvr['hpAll']
        );

        $btl->priemAddLog(
            $id, 1, 2, $u2, $u1, "<span style='color: $color'>$pName</span>", $prv['text'], ($btl->hodID)
        );
    }

    /**
     * Что-то для подключаемых файлов приёмов.
     *
     * @param $uid
     * @param $mg
     * @return bool|mysqli_result|resource
     */
    private function rezadEff($uid, $mg)
    {
        global $btl;
        $md = '';
        $md2 = '';
        $ex = explode('|', $btl->users[$btl->uids[$uid]]['priems']);
        $ex2 = explode('|', $btl->users[$btl->uids[$uid]]['priems_z']);
        $i = 0;
        $ty = [];
        while ($i < count($ex)) {
            if ($ex[$i] > 0) {
                $md .= '`id` = "' . ((int)$ex[$i]) . '" OR ';
                $ty[$ex[$i]] = $i;
            }
            $i++;
        }
        $md = rtrim($md, ' OR ');
        if ($md != '') {
            $md = '( ' . $md . ' ) AND ';
        }
        $sp = mysql_query('SELECT * FROM `priems` WHERE ' . $md . ' `img` LIKE "%' . $mg . '%"');
        while ($pl = mysql_fetch_assoc($sp)) {
            $ex2[$ty[$pl['id']]] = 0;
        }
        $md2 = implode('|', $ex2);
        $btl->users[$btl->uids[$uid]]['priems_z'] = $md2;
        $this->u->info['priems_z'] = $md2;
        $upd = mysql_query('UPDATE `stats` SET `priems_z` = "' . $md2 . '" WHERE `id` = "' . ((int)$uid) . '" LIMIT 1');
        unset($md, $md2, $ty);
        return $upd;
    }

    /** Приём: Вспышка.
     * Файлы: 34, 67, 68, 69.
     * @param        $level
     * @param Battle $btl
     * @param        $id
     * передаётся через pruse() в номерной файл и вызывается оттуда.
     * @return void
     */
    private function fireFlash($level, Battle $btl, $id)
    {
        if (empty($this->ue) || $this->ue['hpNow'] <= 0 || $btl->users[$this->ue['id']]['team'] == $this->u->info['team']) {
            return;
        }

        $baseDamage = [8 => 40, 9 => 45, 10 => 50, 11 => 60];
        $pvr = [];
        $magicTargetTier = Db::getValue(
            'select x from eff_users where uid = ? and v2 = 26 and `delete` = 0',
            [$this->ue['id']]
        );
        $leveledDamage = $baseDamage[$level] + 40 / 100 * (5 * $magicTargetTier);

        [$damage, $isCrit, $isMiss] = $this->magicAttack(
            $btl, $this->u->info['id'], $this->ue['id'], $leveledDamage, self::FIRE, 1
        );
        //Используем проверку на урон приемов
        $damage = $btl->testYronPriem(
            $this->u->info['id'], $this->ue['id'], 21, $damage, 5,
            true
        );
        $btl->priemYronSave($this->u->info['id'], $this->ue['id'], $damage, 0);

        $this->ue['hpNow'] -= $damage;
        $this->ue['hpNow'] = $this->zeromax($this->ue['hpNow'], $this->ue['hpAll']);

        $btl->stats[$btl->uids[$this->ue['id']]]['hpNow'] = $this->ue['hpNow'];

        Db::sql('update stats set hpnow = ? where id = ?', [$this->ue['hpNow'], $this->ue['id']]);

        if ($isMiss) {
            $color = $this->logColor['miss'];
        } elseif ($isCrit) {
            $color = $this->logColor['crit'];
        } else {
            $color = $this->logColor[self::FIRE];
        }
        $btl->priemAddLog(
            $id,
            1,
            2,
            $this->u->info['id'],
            $this->ue['id'],
            "<span style^^^^'color: $color'>Вспышка [$level]</span>",
            '{tm1}' . sprintf(
                " %s <b style='color: %s'>%s</b> [%d/%d]",
                $btl->addlt(1, 19, $this->u->info['sex'], null),
                $pvr['color'],
                $isMiss ? '--' : -$damage,
                (int)$this->ue['hpNow'],
                (int)$this->ue['hpAll']
            ),
            $btl->hodID + 1
        );
    }

    /** Приём: Цель {стихия}
     * Файлы: 25, 26, 27, 28.
     * @param        $element
     * @param        $pl
     * @param        $id
     * @param Battle $btl
     * @return bool (bool) достигнут ли лимит по стаку заклинаний.
     */
    private function magicTarget($element, $pl, $id, Battle $btl)
    {
        $data = [
            self::WATER => [25, 'воды'],
            self::FIRE => [26, 'огня'],
            self::AIR => [27, 'воздуха'],
            self::EARTH => [28, 'земли'],
        ];
        if (!in_array($element, array_keys($data)) || empty($this->ue)) {
            return false;
        }

        $stacked = Db::getRow(
            'select id, x from eff_users where uid = ? and v2 = ? and `delete` = 0',
            [$this->ue['id'], $data[$element][0]]
        );
        $stackNumStr = $stacked['x'] > 0 ? $stacked['x'] + 1 : '';
        if ($stacked['x'] >= 5) {
            echo "<b style='color: {$this->logColor['crit']};'>На пероснаже достигнуто максиальное количество целей</b>";
            return true;
        }

        // Наброс эффекта от приёма.
        $this->addEffPr($pl, $id);

        $dataStr = $stacked['x'] > 0 ? Db::getValue(
            'select data from eff_users where id = ?',
            [$stacked['id']]
        ) : $pl['date3'];

        // Костыль. Будет работать, пока приём изменяет ОДИН параметр.
        $effect = "Защита от магии {$data[$element][1]}: " . current(Conversion::dataStringToArray($dataStr));
        $color = $this->logColor[$element];

        $name = "Цель {$data[$element][1]}";
        if ($stacked['x'] > 0) {
            $name .= " x($stackNumStr)";
        }

        $btl->priemAddLog(
            $id,
            1,
            2,
            $this->u->info['id'],
            $this->ue['id'],
            "<span style^^^^'color: $color'>$name</span>",
            '{tm1}' . sprintf(
                " %s. <i>(%s)</i>",
                $btl->addlt(1, 19, $this->u->info['sex'], null), $effect
            ),
            $btl->hodID
        );

        return false;
    }

    private function addEffPr($pl, $id)
    {
        global $u, $btl;
        $rcu = false;
        $j = Conversion::dataStringToArray($pl['date2']);
        $mpr = false;
        $addch = 0;
        $uid = $this->u->info['id'];
        if (isset($this->ue['id'])) {
            $uid = $this->ue['id'];
        }
        if (isset($j['onlyOne'])) {
            $mpr = Db::getRow(
                'select * from eff_users where v2 = ? and uid = ? and `delete` = 0 and mark = 1',
                [$pl['id'], $uid]
            );
            //$mpr = mysql_fetch_assoc(mysql_query('SELECT * FROM `eff_users` WHERE `v2` = "' . $pl['id'] . '" AND `uid` = "' . $uid . '" AND `delete` = "0" AND `mark` = 1 LIMIT 1'));
        }

        //        if ($pl['cancel_eff2'] != '') {
        //            $i = 0;
        //            $e = explode(',', $pl['cancel_eff2']);
        //            while ($i < count($e)) {
        //                if ($e[$i] > 0) {
        //                    $nem = mysql_fetch_assoc(mysql_query('SELECT * FROM `eff_users` WHERE `uid` = "' . $uid . '" AND `v1` = "priem" AND `v2` = "' . $e[$i] . '" AND `delete` = "0" AND `mark` = 1 LIMIT 1'));
        //                    if (isset($nem['id'])) {
        //                        $nem['priem'] = mysql_fetch_assoc(mysql_query('SELECT * FROM `priems` WHERE `id` = "' . $e[$i] . '" LIMIT 1'));
        //                        if (isset($nem['id'])) {
        //                            $btl->delPriem($nem, $btl->users[$btl->uids[$uid]], 2);
        //                            if ($nem['id'] == $mpr['id']) {
        //                                unset($mpr);
        //                            }
        //                        }
        //                    }
        //                }
        //                $i++;
        //            }
        //        }

        if (!empty($pl['cancel_eff2'])) {
            $this->cancelEffects($pl['cancel_eff2'], $uid, $btl);
        }

        $pld = [0 => ''];
        $nc = 0;
        if (isset($mpr['id']) && $j['onlyOne'] == 1) {
            //отнимаем тактики
            $addch = 1;
            $this->mintr($pl);
            $this->uppz($pl, $id);
            //добавляем прием в эффекты
            if (isset($this->ue['id'])) {
                $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->ue, 0);
            } else {
                $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->u->info, 0);
            }
            $nc = 1;
        } elseif (!isset($mpr['id'])) {
            $data = '';
            if (isset($j['date3Plus'])) {
                $data = $this->redate($pl['date3'], $this->u->info['id']);
            }

            $hd1 = -1;
            if ($pl['limit'] > 0) {
                $tm = 77;
                $hd1 = $pl['limit'];
            } else {
                $tm = 77;
            }
            if ($pl['limit'] == -2) {
                $hd1 = $pl['limit'];
            }
            if ($pl['id'] == 239) //Вывод приемов которые не моментальные как бы
            {
                $btl->priemAddLogFast(
                    $uid, 0, $pl['name'],
                    '{tm' . $this->u->info['team'] . '} ' . $btl->addlt(
                        1, 17, $btl->users[$btl->uids[$uid]]['sex'],
                        null
                    ) . '',
                    1, time()
                );
            }

            $uu = $pl['id'] === 260 ? '' : $this->u->info['id'];
            Db::sql(
                'insert into eff_users (hod, v1, v2, img2, id_eff, uid, name, data, overtype, timeuse, user_use) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                [$hd1, 'priem', $pl['id'], $pl['img'] . '.gif', 22, $uid, $pl['name'], $data, 0, $tm, $uu]
            );

            unset($hd1, $uu);
            //отнимаем тактики
            $addch = 1;
            $rcu = true;
            $nc = 1;
            $this->mintr($pl);
            //$this->uppz($pl,$id);
            //добавляем прием в эффекты
            if (isset($this->ue['id'])) {
                $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->ue, 0);
            } else {
                $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->u->info, 0);
            }
        } elseif ($j['onlyOne'] > 1) {
            if ($mpr['x'] < $j['onlyOne'] && isset($j['date3Plus'])) {
                $j1 = Conversion::dataStringToArray($mpr['data']);
                $j2 = Conversion::dataStringToArray($this->redate($pl['date3'], $this->u->info['id']));
                $v = $this->u->lookKeys($this->redate($pl['date3'], $this->u->info['id']), 0); // ключи 2
                //добавляем данные друг к другу
                $i = 0;
                $inf = '';
                while ($i < count($v)) {
                    $j1[$v[$i]] += $j2[$v[$i]];
                    $vi = str_replace('add_', '', $v[$i]);
                    if ($this->u->is[$vi] != '') {
                        if ($j2[$v[$i]] > 0) {
                            $inf .= $this->u->is[$vi] . ': +' . ($j2[$v[$i]] * (1 + $mpr['x'])) . ', ';
                        } elseif ($j2[$v[$i]] < 0) {
                            $inf .= $this->u->is[$vi] . ': ' . ($j2[$v[$i]] * (1 + $mpr['x'])) . ', ';
                        }
                    }
                    $i++;
                }
                $inf = rtrim($inf, ', ');
                $j1 = Conversion::arrayToDataString($j1);
                $pld[0] = ' x' . ($mpr['x'] + 1);
                if ($j['refHod'] == 1) {
                    $mpr['hod'] = $pl['limit'];
                }
                $upd = mysql_query(
                    'UPDATE `eff_users` SET `hod` = "' . $mpr['hod'] . '",`data` = "' . $j1 . '",`x` = `x`+1 WHERE `id` = "' . $mpr['id'] . '" LIMIT 1'
                );
                if ($upd) {
                    //отнимаем тактики
                    $this->mintr($pl);
                    $this->uppz($pl, $id);
                    //добавляем прием в эффекты
                    if (isset($this->ue['id'])) {
                        $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->ue, 0);
                    } else {
                        $btl->stats[$btl->uids[$uid]] = $this->u->getStats($this->u->info, 0);
                    }
                    $addch = 1;
                    $rcu = true;
                    $nc = 1;
                }
            }
        }
        /* тратим свой ход */
        if ($nc == 1 && $pl['tr_hod'] > 0) {
            $this->trhod($pl);
        }
        //return $rcu;
    }

    public function mintr($pl)
    {
        global $u, $btl;
        $x = 1;
        $rt = '';
        while ($x <= 7) {
            if ($pl['ndt' . $x] == 0) {
                $this->u->info['tactic' . $x] -= $pl['tt' . $x];
                $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] -= $pl['tt' . $x];
            }
            if ($this->u->info['tactic' . $x] < 0) {
                $this->u->info['tactic' . $x] = 0;
            }
            if ($btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] < 0) {
                $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] = 0;
            }
            //$rt .= ',`tactic'.$x.'`="'.$this->u->info['tactic'.$x].'"';
            $rt .= ',`tactic' . $x . '`="' . $btl->users[$btl->uids[$this->u->info['id']]]['tactic' . $x] . '"';
            $x++;
        }
        if ($pl['xuse'] > 0) {
            $this->u->addAction(time(), 'use_priem_' . $btl->i->id . '_' . $this->u->info['id'], $pl['id']);
        }
        $rt = ltrim($rt, ',');
        mysql_query('UPDATE `stats` SET ' . $rt . ' WHERE `id` = "' . $this->u->info['id'] . '" LIMIT 1');
    }

    /** Пожирающее пламя. Первичный каст на противника, на котором нет эффекта.
     * Кастуется на 5 ходов. Считает сколько урона будет наноситься следующие 5 ходов.
     * Конечный damage после множителей делится на 5 и пишется в БД (atgm=).
     * Файлы: 33, 56, 57, 58, 59, 60.
     * @param        $id
     * @param array $pl массив значений из БД priems.
     * @param Battle $btl
     * @return void
     */
    private function devouringFlameInit($id, array $pl, Battle $btl)
    {
        $baseDamage = [6 => 53, 7 => 63, 8 => 77, 9 => 91, 10 => 110, 11 => 133,];
        [$damage, , $isMiss] = $this->magicAttack(
            $btl, $this->u->info['id'], $this->ue['id'], $baseDamage[$pl['level']], self::FIRE
        );
        if ($isMiss || $damage <= 0) {
            return;
        }

        $color = $this->logColor[self::FIRE];
        $logText = '{tm1}' . $btl->addlt(1, 19, $btl->users[$btl->uids[$this->u->info['id']]]['sex'], null) . '.';
        $btl->priemAddLog(
            $id, 1, 2, $this->u->info['id'], $this->ue['id'], "<span style^^^^'color: $color'>{$pl['name']}</span>",
            $logText, $btl->hodID + 1
        );

        $data = Conversion::arrayToDataString(['atgm' => max(floor($damage / 5), 1)]);

        $this->addPriem(
            $this->ue['id'], $pl['id'], $data, 0, 77, 5, $this->u->info['id'], 1, 'пожирающеепламя', 0, 0, 1
        );
    }

    /** Кристаллизация. Отнимает от максимального стата (кроме выносливости) 20 на 3 хода.
     * Если есть одинаковые статы из них выбирается случайный.
     * Файл:267, приём 268. Понимай как хочешь.
     * @param        $id
     * @param array $pl
     * @param Battle $btl
     * @return void
     */
    private function crystalize($id, array $pl, Battle $btl)
    {
        $q = 'select stats as data from stats where id = ?
                union all select stats as data from test_bot where id = ?
                union all select data from eff_users where `delete` = 0 and uid = ?
                union all select data from items_users where inodet > 0 and `delete` = 0 and uid = ?';
        $datas = Db::getColumn($q, array_fill(0, 3, $this->ue['id']));
        $stats = array_fill_keys(['s1', 's2', 's3', 's5', 's6'], 0);
        foreach ($datas as $data) {
            $data = Conversion::dataStringToArray($data);
            print_r($data);
            foreach (array_keys($stats) as $stat) {
                if (isset($data[$stat])) {
                    $stats[$stat] += $data[$stat];
                }
                if (isset($data['add_' . $stat])) {
                    $stats[$stat] += $data['add_' . $stat];
                }
            }
        }
        $maxValue = max($stats);
        $maxKeys = [];

        foreach ($stats as $k => $v) {
            if ($maxValue == $v) {
                $maxKeys[] = $k;
            }
        }
        shuffle($maxKeys);
        $datastr = "|add_{$maxKeys[0]}=-20";
        $debuffstr = "Замороженная " . mb_strtolower($this->u->is[$maxKeys[0]]);

        $color = $this->logColor[self::WATER];
        $logText = '{tm1}' . $btl->addlt(1, 19, $btl->users[$btl->uids[$this->u->info['id']]]['sex'], null) . '.';
        $btl->priemAddLog(
            $id, 1, 2, $this->u->info['id'], $this->ue['id'],
            "<span style^^^^'color: $color'>{$pl['name']}:</span> $debuffstr", $logText, $btl->hodID + 1
        );

        $this->addPriem($this->ue['id'], 268, $datastr, 2, 77, 3, $this->u->info['id'], 3, 0, 0, 1);
    }

}