<?php

use Core\Db;

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

/* CRON Завершение поединка и удаление из заявок */

# Запуск раз в минуту.

function getIds($query): string
{
    return implode(',', Db::getColumn($query));
}

# HOUR = 1800
Db::sql(
'update users
    left join battle on users.battle = battle.id
    left join battle_logs on battle_logs.id = battle.id
set
    users.battle = 0,
    battle.team_win = 0,
    battle.time_over = unix_timestamp()
where
    battle.team_win = -1 and
    battle.time_start < unix_timestamp() - 1800 * 2 and
    battle_logs.time < unix_timestamp() - 1800 *2'
);

$bid = Db::getColumn('select id from battle where time_start < unix_timestamp() - 180 and team_win = -1 and typeBattle = 9');
foreach ($bid as $item) {
    $count = Db::getValue('select count(*) from users where battle = ?', [$item]);
    if ($count < 8) {
        $timeout = 60;
    } elseif ($count < 12) {
        $timeout = 120;
    } else {
        $timeout = 180;
    }
    Db::sql('update battle set timeout = ? where id = ?', [$timeout, $item]);
}
unset($bid);
Db::sql('delete from battle_cache where time < unix_timestamp() - 3600');


//$bid = getIds('select id from battle where type = 33 and (time_over < unix_timestamp() - 120 or time_over > unix_timestamp() - 360)');

////дичь, невыполнимое условие: `time_over` < "'.(time()-120).'" AND `time_over` > "'.(time() - 360).'" AND `time_over` != 0
//// уточнить реализацию

//вытаскиваем персов из приз хаота если застрЯли (1-5 минут окончание)
//$sp = mysql_fetch_array(mysql_query('SELECT * FROM `battle` WHERE `type` = 33 AND `time_over` < "'.(time()-120).'" AND `time_over` > "'.(time() - 360).'" AND `time_over` != 0 ORDER BY `battle`.`time_over` DESC LIMIT 1'));
//if (isset($sp['id']))
//	{
//		mysql_query('UPDATE `battle` SET `time_over` = `time_over` - 300 WHERE `id` = "'.$sp['id'].'" LIMIT 1');
//		$sps = mysql_query('SELECT * FROM `users` WHERE `mail` LIKE "haot@new-combats.com" AND `battle` = 0');
//		while( $pl = mysql_fetch_array($sps))
//		{
//			if (isset($pl['id']))
//			{
//				mysql_query('UPDATE `users` SET `inUser` = "0" WHERE `inUser` = "'.$pl['id'].'" LIMIT 1');
//				mysql_query('DELETE FROM `users` WHERE `id` = "'.$pl['id'].'" LIMIT 1');
//				mysql_query('DELETE FROM `stats` WHERE `id` = "'.$pl['id'].'" LIMIT 1');
//				mysql_query('DELETE FROM `items_users` WHERE `uid` = "'.$pl['id'].'" LIMIT 100');
//				mysql_query('DELETE FROM `eff_users` WHERE `uid` = "'.$pl['id'].'" LIMIT 100');
//			}
//		}
//	}


//‚ытаскиваем персов если застрЯли в боЯх

//todo, всё, ничего не соображаю. доделать запрос, чтобы он учитывал:  || !isset($test['id']

//'update users
//    left join stats on users.id = stats.id
//    left join battle on users.id = battle.id
//set
//    users.battle = 0,
//    stats.battle_yron = 0
//where
//    users.battle > 0 and
//    battle.time_over between 1 and unix_timestamp() - 600';

$sps = mysql_query('SELECT * FROM `users` WHERE `battle` > 0');
while( $pl = mysql_fetch_array($sps))
	{
		if (isset($pl['id']))
		{
			$test = mysql_fetch_array(mysql_query('SELECT * FROM `battle` WHERE `id` =  "'.$pl['battle'].'" LIMIT 1'));
			if (($test['time_over'] < (time()-600) && $test['time_over'] !=0) || !isset($test['id']))
			{
				mysql_query('UPDATE `users` SET `battle`= 0 WHERE `id` = "'.$pl['id'].'" LIMIT 1');
				mysql_query('UPDATE `stats` SET `battle_yron` = 0 WHERE `id` = "'.$pl['id'].'" LIMIT 1');
			}
		}
	}
//чистим памЯть
unset($sp,$sps,$pl,$test);