<?php
/**
 * Copyright (c) 2018.
 * Author: Igor Barkov <lopar.4ever@gmail.com>
 * Project name: Battles-Game
 */

use Battles\GameLogs;
use Battles\Nick;

include_once '../config.php';
include_once '../functions.php';
$tm = time();

##########
$zayavka = db::c()->query('SELECT `id`,`start`,`level`,`t1c`,`team1`,`t2c`,`team2` FROM `zayavka`')->fetch_assoc();
while ($zayavka) {
    if ($zayavka['start'] <= time()) {
        if ($zayavka['level'] == 4 || (($zayavka['t1c'] == count($zayavka['team1'])) && ($zayavka['t2c'] == count($zayavka['team2'])))) {
            startbattle("CHAOS", $zayavka['id'], 4);
        } elseif ($zayavka['level'] == 5) {
            startbattle("CHAOS", $zayavka['id'], 5);
        }
    }
}

function fteam($team)
{
    $team = explode(";", $team);
    unset($team[count($team) - 1]);
    return $team;
}

function getlist($razdel = 1, $level = null, $id = null)
{
    $fict = mysql_query("SELECT * FROM `zayavka` WHERE " . (($level != null) ? " ((`t1min` <= '{$level}' OR `t1min` = '99') AND (`t1max` >= '{$level}' OR `t1max` = '99') " . (($razdel == 4) ? "AND (`t2min` <= '{$level}' OR `t2min` = '99') AND (`t2max` >= '{$level}' OR `t2max` = '99')" : "") . ") AND " : "") . " `level` = {$razdel} " . (($id != null) ? " AND `id` = {$id} " : "") . " ORDER BY `podan` DESC");
    while ($row = mysql_fetch_array($fict)) {
        if (($row['start'] + 300) < time()) {
            if (mysql_query("DELETE FROM `zayavka` WHERE `id` = '{$row['id']}' LIMIT 1")) {
                $team1 = fteam($row['team1']);
                foreach ($team1 as $k => $v) {
                    mysql_query("UPDATE `users` SET `zayavka` = '0' WHERE `id` = {$v}");
                }
                $team2 = fteam($row['team2']);
                foreach ($z[$zay]['team2'] as $k => $v) {
                    mysql_query("UPDATE `users` SET `zayavka` = '0' WHERE `id` = {$v}");
                }
            }
        }
        $zay[$row['id']] = ["team1" => fteam($row['team1']), "team2" => fteam($row['team2']), "coment" => $row['coment'], "type" => $row['type'], "timeout" => $row['timeout'], "start" => $row['start'], "t1min" => $row['t1min'], "t1max" => $row['t1max'], "t2min" => $row['t2min'], "t2max" => $row['t2max'], "t1c" => $row['t1c'], "t2c" => $row['t2c'], "podan" => $row['podan'], "id" => $row['id'], "level" => $row['level'], "blood" => $row['blood'], "bots" => $row['bots']];
    }
    return $zayavka;
}

function delzayavka($id, $zay, $r)
{
    $z = getlist($r, null, $zay);
    if ($z[$zay]['level'] > 3) {
        return 'Ай-ай-ай!';
    }
    if (db::c()->query('DELETE FROM `zayavka` WHERE `id` = ?i AND (`team1` LIKE "?S" OR `team2` LIKE "?S")', $zay, $id.';%', $id.';%')) {
        if (count($z[$zay]['team1']) > 0) {
            foreach ($z[$zay]['team1'] as $k => $v) {
                db::c()->query('UPDATE `users` SET `zayavka` = 0 WHERE `id` = ?i', $v);
            }
        }
        if (count($z[$zay]['team2']) > 0) {
            foreach ($z[$zay]['team2'] as $k => $v) {
                db::c()->query('UPDATE `users` SET `zayavka` = 0 WHERE `id` = ?i', $v);
            }
        }
    }
    return true;
}

function startbattle($id, $zay, $r)
{
    $z = getlist($r, null, $zay);
    if ($id == 'CHAOS') {
        $id = $z[$zay]['team1'][0];
    }
    delzayavka($id, $zay, $r);
    $z = $z[$zay];
    $count_users = count($z['team1']);

    if ($z['bots'] > 0 && $count_users > 0) {
        $bots_raw = [7 => [10962, 10964, 10965], 8 => [10962, 10964, 10965], 13 => [10962, 10964, 10965]];
        $i = 0;
        while ($i <= count($bots_raw[$z['bots']])) {
            $bot_id = $bots_raw[$z['bots']][$i];
            $bot = createbot($bot_id, '');
            $z['team1'][] = $bot['id'];
            $i++;
            $count_users++;
        }
    }

    // Групповой/хаотический бой накрылся потому что меньше 4 человек.
    if ($z['type'] == 3 || $z['type'] == 5) {
        if ($count_users < 4) {
            db::c()->query('UPDATE `users` SET `zayavka` = 0 WHERE `zayavka` = ?i', $zay);
            foreach ($z['team1'] as $k => $v) {
                if ($v < _BOTSEPARATOR_) {
                    // Сообщение в чат: Ваш бой не может начаться, группа не набрана.
                    file_get_contents(GAMEDOMAIN . '/chats.php?id=6&user=' . $v);
                }
            }
            db::c()->query('UPDATE `variables` SET `value` = "?s" WHERE `var` = "?s"', $count_users, 'haos_match');
            db::c()->query('DELETE FROM `zayavka` WHERE `id` = ?i', $zay);
        }

        $all = count($z['team1']) - 1;
        $power1 = 0;
        $power2 = 0;

        for ($i = 0; $i <= $all; $i++) {
            if ($z['team1'][$i] < _BOTSEPARATOR_) {
                $gamer = mysql_fetch_array(mysql_query("SELECT (`level`*50)+`sila`+`lovk`+`inta`+`vinos`+`intel`+`stats`+IFNULL((SELECT SUM(`cost`) FROM `inventory` WHERE `owner` = `users`.`id` AND `dressed` = 1), 0) FROM `users` WHERE `id` = '" . $z['team1'][$i] . "' LIMIT 1"));
            } else {
                $bt = mysql_fetch_array(mysql_query('SELECT `id`, `prototype` FROM `bots` WHERE `id` = "' . $z['team1'][$i] . '"'));
                $gamer = mysql_fetch_array(mysql_query("SELECT (`level`*50)+`sila`+`lovk`+`inta`+`vinos`+`intel`+`stats`+IFNULL((SELECT SUM(`cost`) FROM `inventory` WHERE `owner` = `users`.`id` AND `dressed` = 1), 0) FROM `users` WHERE `id` = '" . $bt['prototype'] . "' LIMIT 1"));
            }

            $cost[] = [$z['team1'][$i], $gamer[0]];
        }

        $z['team1'] = null;
        $z['team2'] = null;

        $flag = true;
        while ($flag) {
            $flag = false;
            for ($ii = 0; $ii <= $all - 1; $ii++) {
                if ($cost[$ii][1] < $cost[$ii + 1][1]) {
                    $ctr = $cost[$ii + 1];
                    $cost[$ii + 1] = $cost[$ii];
                    $cost[$ii] = $ctr;
                    $flag = true;
                }
            }
        }

        while (count($cost) > 0) {
            if ($power1 <= $power2) {
                $tmp = array_shift($cost);
                $power1 += $tmp[1];
                $z['team1'][] = $tmp[0];
            } else {
                $tmp = array_shift($cost);
                $power2 += $tmp[1];
                $z['team2'][] = $tmp[0];
            }
        }
    }

    $teams = [];

    foreach ($z['team1'] as $k => $v) {
        foreach ($z['team2'] as $kk => $vv) {
            $teams[$v][$vv] = [0, 0, time()];
        }
    }

    foreach ($z['team2'] as $k => $v) {
        foreach ($z['team1'] as $kk => $vv) {
            $teams[$v][$vv] = [0, 0, time()];
        }
    }

    if (count($z['team2']) == 0) {
        mysql_query("UPDATE `users` SET `zayavka` = 0 WHERE `zayavka` = '" . $zay . "'");
        foreach ($z['team1'] as $k => $v) {
            file_get_contents(GAMEDOMAIN . '/chats.php?id=6&user=' . $v);
        }
        mysql_query("DELETE FROM `zayavka` WHERE `id` = '" . $zay . "' LIMIT 1");
        exit;
    }

    $z['timeout'] = 3;

    if ($z['type'] == 1 || $z['type'] == 4) {
        $rs = ', `fiz`';
        $rss = ', 1';
    } else {
        $rs = '';
        $rss = '';
    }

    mysql_query("INSERT INTO `battle` (`coment`, `teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`$rs, `bots`) VALUES ('{$z['coment']}', '" . serialize($teams) . "', '{$z['timeout']}', '{$z['type']}', '0', '" . implode(";", $z['team1']) . "', '" . implode(";", $z['team2']) . "', '" . time() . "', '" . time() . "', '" . $z['blood'] . "'$rss, '" . $z['bots'] . "')");
    $id = mysql_insert_id();
    $rr = "<b>";

    foreach ($z['team1'] as $k => $v) {
        if ($k != 0) {
            $rr .= ", ";
        }
        $rr .= Nick::id($v)->full(1);
        file_get_contents(GAMEDOMAIN . '/chats.php?id=7&user=' . $v);
    }

    $rr .= "</b> и <b>";

    foreach ($z['team2'] as $k => $v) {
        if ($k != 0) {
            $rr .= ", ";
        }
        $rr .= Nick::id($v)->full(1);
        file_get_contents(GAMEDOMAIN . '/chats.php?id=7&user=' . $v);
    }

    $rr .= "</b>";
    GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу.<BR>");

    foreach ($z['team1'] as $k => $v) {
        if ($v < _BOTSEPARATOR_) {
            mysql_query("UPDATE `users` SET `battle` = {$id}, `zayavka` = 0 WHERE `id` = {$v}");
        } else {
            mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE `id` = {$v}");
        }
    }

    foreach ($z['team2'] as $k => $v) {
        if ($v < _BOTSEPARATOR_) {
            mysql_query("UPDATE `users` SET `battle` = {$id}, `zayavka` = 0 WHERE `id` = {$v}");
        } else {
            mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE `id` = {$v}");
        }
    }
}

##########

########Start Заявки для ботов в хаоты########
$battle_bots = mysql_fetch_array(mysql_query('SELECT `id` FROM `battle` WHERE `win` = 3 AND `bots` > 0 ORDER BY `id` DESC LIMIT 1'));
$zay_bots = mysql_fetch_array(mysql_query('SELECT `id` FROM `zayavka` WHERE `bots` > 0 ORDER BY `id` DESC LIMIT 1'));

if (!isset($battle_bots['id']) && !isset($zay_bots['id'])) {
    $haos_match = [];
    $hm_ok = [7 => 1];
    foreach ($hm_ok as $lvl => $flag) {
        if ($flag == 1) {
            mysql_query("INSERT INTO `zayavka` (`start`, `timeout`, `t1c`, `t2c`, `type`, `level`, `coment`, `team1`, `stavka`, `t1min`, `t2min`, `t1max`, `t2max`, `podan`, `blood`, `bots`) VALUES ('" . (time() + 3 * 60) . "', '3', '99', '99', '3', '5', '<u>Бой с силами Хаоса <b>{$lvl}</b> уровня.</u>', '', '', '{$lvl}', '{$lvl}', '{$lvl}', '{$lvl}', '" . date("H:i") . "', '0', '{$lvl}')");
            $haos_match[$lvl] = mysql_insert_id();
        }
    }
    file_get_contents(GAMEDOMAIN . '/chats.php?id=1');
}
########End Заявки для ботов в хаоты########


######
$te_zay = mysql_query('SELECT `id`, `start` FROM `zayavka`');
while ($zs = mysql_fetch_array($te_zay)) {
    if (($zs['start'] + 180) < time()) {
        mysql_query('UPDATE `users` SET `zayavka` = "0" WHERE `zayavka` = "' . $zs['id'] . '"');
        mysql_query('DELETE FROM `zayavka` WHERE `id` = "' . $zs['id'] . '"');
    }
}
######

if (date("H-i") == "03-00") {
    $del_tm = (time() - 60 * 60 * 24 * 7);
    $us_lim = mysql_fetch_array(mysql_query("SELECT `id` FROM `battle` WHERE `to1` < '{$del_tm}' ORDER BY `to1` DESC LIMIT 1"));
    $us_lim = $us_lim['id'];
    mysql_query("DELETE FROM `battle` WHERE `id` < '{$us_lim}'");
    $del_tm = (time() - 60 * 60 * 24 * 60);
    mysql_query("DELETE FROM `delo` WHERE `date` < '" . $del_tm . "'");
    mysql_query("OPTIMIZE `battle`, `delo`");
}



mysql_query('UPDATE `actions` SET `vals` = "end" WHERE `vars` LIKE "start_quest%" AND `vals` = "go" AND `val` <= "' . time() . '"');


$st_ar = mysql_fetch_array(mysql_query('SELECT `value` FROM `variables` WHERE `var` = "arena_of_gods" LIMIT 1'));
if ($st_ar['value'] <= time()) {
    $dark = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `level`, `hp` FROM `users` WHERE `id` = 10023 LIMIT 1'));
    $light = mysql_fetch_array(mysql_query('SELECT `id`, `login`, `level`, `hp` FROM `users` WHERE `id` = 10024 LIMIT 1'));
    ##############
    mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`, `owner`) VALUES ('" . $light['login'] . "', '" . $light['id'] . "', '', '" . $light['hp'] . "', '1')");
    $light['id_at'] = mysql_insert_id();
    mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('" . $dark['login'] . "', '" . $dark['id'] . "', '', '" . $dark['hp'] . "')");
    $dark['id_at'] = mysql_insert_id();
    ##############
    $teams = [];
    $teams[$dark['id_at']][$light['id_at']] = [0, 0, time()];
    $teams[$light['id_at']][$dark['id_at']] = [0, 0, time()];
    mysql_query("INSERT INTO `battle` (`id`, `coment`, `teams`, `time_m`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`, `aren_of`) VALUES (NULL, '', '" . serialize($teams) . "', '" . time() . "', '3', '1', '0', '" . $dark['id_at'] . "', '" . $light['id_at'] . "', '" . time() . "', '" . time() . "', '1', '1')");
    $id = mysql_insert_id();
    mysql_query("UPDATE `bots` SET `battle` = {$id} WHERE (`id` = {$dark['id_at']} OR `id` = {$light['id_at']}) LIMIT 2");
    $rr = "<b>" . Nick::id($dark['id_at'])->full(1) . "</b> и <b>" . Nick::id($light['id_at'])->full(1) . "</b>";
    GameLogs::addBattleLog($id, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <br />");
    mysql_query("UPDATE `users` SET `battle` = {$id}, `zayavka` = 0 WHERE (`id` = {$dark['id']} OR `id` = {$light['id']}) LIMIT 2");
    file_get_contents(GAMEDOMAIN . '/chats.php?id=2');
    mysql_query('UPDATE `variables` SET `value` = "' . (time() + 60 * 60 * 24 * 7) . '" WHERE `var` = "arena_of_gods" LIMIT 1');
}

$st_ar['value'] -= 3600;
if (date("z-H-i") == date("z-H-i", $st_ar['value'])) {
    file_get_contents(GAMEDOMAIN . '/chats.php?id=3');
}

$komp_users = mysql_query("SELECT * FROM `users`, `online` WHERE `users`.`id` = `online`.`id` AND `online`.login_time >= " . (time() - 60) . "");
while ($ku = mysql_fetch_array($komp_users)) {
    $bns = 0;
    $efs_bns = mysql_fetch_array(mysql_query('SELECT SUM(`hp`) AS `hps` FROM `effects` WHERE `owner` = "' . $ku['id'] . '"'));
    if ($efs_bns['hps'] > 0) {
        $bns = $efs_bns['hps'];
    }
    mysql_query("UPDATE `users` SET `maxhp` = (IFNULL((SELECT SUM(`ghp`) FROM `inventory` WHERE `dressed` = 1 AND `owner` = `users`.`id`),0) + (`users`.`vinos`*6)+$bns) WHERE `id` = '{$ku['id']}'");
}

db::c()->query('UPDATE `users` SET `hp` = 0 WHERE  `hp` < 0');
db::c()->query('UPDATE `users` SET `mana` = 0 WHERE  `mana` < 0');


$effs = mysql_query("SELECT * FROM `effects` WHERE `time` <= " . time() . " AND `sleep` = 0");
mysql_query("DELETE FROM `effects` WHERE `time` <= " . time() . " AND `sleep` = 0");
while ($eff = mysql_fetch_array($effs)) {
    switch ($eff['type']) {
        case 11:
            mysql_query("UPDATE `users` SET `sila` = `sila`+'" . $eff['sila'] . "', `lovk` = `lovk`+'" . $eff['lovk'] . "', `inta` = `inta`+'" . $eff['inta'] . "' WHERE `id` = '" . $eff['owner'] . "' ");
            break;
        case 12:
            mysql_query("UPDATE `users` SET `sila` = `sila`+'" . $eff['sila'] . "', `lovk` = `lovk`+'" . $eff['lovk'] . "', `inta` = `inta`+'" . $eff['inta'] . "' WHERE `id` = '" . $eff['owner'] . "' ");
            break;
        case 13:
            mysql_query("UPDATE `users` SET `sila` = `sila`+'" . $eff['sila'] . "', `lovk` = `lovk`+'" . $eff['lovk'] . "', `inta` = `inta`+'" . $eff['inta'] . "' WHERE `id` = '" . $eff['owner'] . "' ");
            break;
        case 14:
            mysql_query("UPDATE `users` SET `sila` = `sila`+'" . $eff['sila'] . "', `lovk` = `lovk`+'" . $eff['lovk'] . "', `inta` = `inta`+'" . $eff['inta'] . "' WHERE `id` = '" . $eff['owner'] . "' ");
            break;
        case 21:
            mysql_query("UPDATE `users` SET `sila` = `sila`-'" . $eff['sila'] . "', `lovk` = `lovk`-'" . $eff['lovk'] . "', `inta` = `inta`-'" . $eff['inta'] . "', `vinos` = `vinos`-'" . $eff['vinos'] . "' WHERE `id` = '" . $eff['owner'] . "' ");
            break;
        case 4:
            mysql_query("UPDATE `users` SET `align` = '0' WHERE `id` = '" . $eff['owner'] . "'");
            break;
        case 7:
            mysql_query("UPDATE `users` SET `maxhp` = (`maxhp`-200), `hp` = `maxhp` WHERE `id` = '" . $eff['owner'] . "'");
            break;
        case 1022:
            mysql_query("UPDATE `users` SET `invis` = 0 WHERE `id` = '" . $eff['owner'] . "' LIMIT 1");
            break;
    }
}

$hostel = mysql_query('SELECT `id`, `sleep` FROM `users` WHERE `sleep` != 0');
while ($pl = mysql_fetch_array($hostel)) {
    if ($pl['sleep'] <= time()) {
        mysql_query('UPDATE `users` SET `sleep` = 0 WHERE `id` = "' . $pl['id'] . '"');
        mysql_query('UPDATE `hostel` SET `sleeptime` = "' . (time() + 60 * 60 * 6) . '" WHERE `uid` = "' . $pl['id'] . '"');
        $ef = mysql_query('SELECT `id`, `time`, `sleep` FROM `effects` WHERE `owner` = "' . $pl['id'] . '" AND `sleep` != 0');
        while ($ps = mysql_fetch_array($ef)) {
            $tm = (time() + $ps['sleep']);
            mysql_query('UPDATE `effects` SET `time` = "' . $tm . '", `sleep` = "0" WHERE `id` = "' . $ps['id'] . '" AND `owner` = "' . $pl['id'] . '"');
        }
    }
}