<?php

use Core\Db;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoload.php';

# Какие-то операции над ботами.
## Этот файл управляет всей логикой всех ботов везде.
## BotLogic::start - очень тяжелый на запросы класс.

# раз в минуту
# Раньше в кроне был дополнительный таймер на обновление каждые 4 секунды.
# Если ботам будет мало минуты, играться таймером.

$uids = implode(
    ',',
    Db::getColumn('select id from users where no_ip = ? or pass = ?', ['trupojor', 'saintlucia'])
);

Db::sql("update stats left join users on stats.id = users.id set exp = 400000 where exp > 400000 and level = 8 and stats.id in ($uids)");
Db::sql("update stats left join users on stats.id = users.id set exp = 3500000 where exp > 3500000 and level = 9 and stats.id in ($uids)");
Db::sql("update stats left join users on stats.id = users.id set exp = 48000000 where exp > 48000000 and level = 10 and stats.id in ($uids)");
Db::sql("update stats left join users on stats.id = users.id set exp = 148000000 where exp > 148000000 and level = 11 and stats.id in ($uids)");
Db::sql("update stats left join users on stats.id = users.id set exp = 400000000 where exp > 400000000 and level = 12 and stats.id in ($uids)");

Db::sql("update users set online = unix_timestamp() where timereg != 0 and id in ($uids)");
Db::sql("update users set timereg = unix_timestamp() where timereg = 0 and id in ($uids)");

Db::sql("update stats set bot = 2 where bot = 0 and id in ($uids)");

Db::sql("update stats set nextAct = unix_timestamp() where id in ($uids)");

# ЧТО ТЫ ТАКОЕ БЛЯТЬ?!
$btltest = [];
$data = Db::getRows('select zv, stats.id, battle from users left join stats on users.id = stats.id where no_ip = ? or pass = ? order by nextAct', ['trupojor', 'saintlucia']);
foreach ($data as $row) {
    if ($row['zv']) {
        $zv = Db::getValue('select razdel from zayvki where id = ? and btl_id = 0 and razdel != 5', [$row['zv']]);
        if ($zv) {
            Db::sql('update stats set zv = 0 where id = ?', [$row['id']]);
            $row['zv'] = 0;
        }
    }
    if ($row['battle']=== -1) {
        Db::sql('update users left join stats on users.id = stats.id set battle = 0, ipreg = 0, zv = 0 where users.id = ?', [$row['id']]);
        $row['battle'] = 0;
    }
    if (in_array(idate('i'), [5, 6, 15, 16, 25, 26, 35, 36, 45]) && $row['zv'] === 0) {
        Db::sql('update users set ipreg = 0 where id = ?', [$row['id']]);
    }

    if ($row['zv'] === 0 && ($row['battle'] === 0 || empty($btltest[$row['battle']]) || $btltest[$row['battle']] < 1)) {
        $btltest[$row['battle']]++;
        Db::sql('update users set online = unix_timestamp(), afk = ? where id = ?', ['', $row['id']]);
        BotLogic::start($row['id']);
    } else {
        Db::sql('update users set online = unix_timestamp() where id = ?', [$row['id']]);
    }
}