<?php

/*
 * Горбунов Александр 
 * https://vk.com/sasha_gorbunov
 * Распространение и перепродажа запрещена
 */
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

class team_war {
    public $id = false;
    public $level = false;
    public $time_dmg = false;
    public $target = false;
    public $kamen = false;
    public $trava = false;

    public function __construct($id = null) {
        $this->id = $id;
        $this->getId();
        $this->getLevel();
        $this->getRock();
        $this->getGrass();
        $this->getTarget();
        $this->getTimeDmg();
        $this->getUserIdBattle();
    }

    protected function UserId() {
        global $user;
        return $user;
    }

    public function getId() {
        $user = $this->UserId();
        return $this->id = $user['id'];
    }

    public function getTimeDmg() {
        $timeDmg = mysql_fetch_assoc(mysql_query('SELECT `time_dmg` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        return $this->time_dmg = $timeDmg['time_dmg'];
    }

    public function getUserIdBattle() {
        $id = mysql_fetch_assoc(mysql_query('SELECT `id_battle` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        mysql_query('UPDATE `users` SET `id_battle` = "' . $id['id_battle'] . '" WHERE `id` = "' . $this->id . '"');
    }

    public function getLevel() {
        $user = $this->UserId();
        return $this->level = $user['level'];
    }

    public function getRock() {
        $trava_time = mysql_fetch_assoc(mysql_query('SELECT `trava` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        return $this->trava = $trava_time['trava'];
    }

    public function getGrass() {
        $grass_time = mysql_fetch_assoc(mysql_query('SELECT `kamen` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        return $this->kamen = $grass_time['kamen'];
    }

    public function spotLevel() {
        $level = $this->level;
        $result = false;
        switch ($level) {
            case ($level >= 10 && $level <= 19):
                $result = 1;
                break;
            case ($level >= 20 && $level <= 29):
                $result = 2;
                break;
            case ($level >= 30 && $level <= 39):
                $result = 3;
                break;
            case ($level >= 40 && $level <= 49):
                $result = 4;
                break;
            case ($level >= 50 && $level <= 59):
                $result = 5;
                break;
            case ($level >= 60 && $level <= 69):
                $result = 6;
                break;
        }
        return $result;
    }

    public function getDead() {
        if (mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '" AND `dead` = "1" AND `fight` = "2"'), 0) == true) {
            # Убит
            return true;
        }
        return false;
    }

    public function setCheckQueue() {
        $user = $this->UserId();
        if (mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'), 0) == false) {
            mysql_query('INSERT INTO `avenax_team_battle` (`id_user`, `level`, `health`, `fight`) ' . 'VALUES ("' . $this->id . '", "' . $this->spotLevel() . '", "' . $user['max_health'] . '", "1")');
            $_SESSION['msg'] = 'Вы стали в очередь!';
        } else {
            mysql_query('DELETE FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"');
            $_SESSION['msg'] = 'Вы покинули очередь!';
        }
    }

    public function getCheckQueue() {
        if (mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'), 0) == false) {
            return false;
        }
        return true;
    }

    public function getCheckFight() {
        if (mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '" AND `fight` = "2"'), 0) == false) {
            return false;
        }
        return true;
    }

    public function getCountPlayerLevel() {
        $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `level` = "' . $this->spotLevel() . '" AND `fight` = "1"'), 0);
        return $count;
    }

    public function getCountPlayerBattle() {
        $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `level` = "' . $this->spotLevel() . '" AND `fight` = "2" AND `dead` = "0"'), 0);
        return $count;
    }

    public function getCountPlayers() {
        $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `fight` = "1"'), 0);
        return $count;
    }

    function getTime($time) {

        $time_battle = array(
            strtotime(date("Y-m-d 07:00:00")), // 0
            strtotime(date("Y-m-d 09:00:00")), // 1
            strtotime(date("Y-m-d 11:00:00")), // 2
            strtotime(date("Y-m-d 13:00:00")), // 3
            strtotime(date("Y-m-d 15:00:00")),
            strtotime(date("Y-m-d 17:00:00")),
            strtotime(date("Y-m-d 19:00:00")),
            strtotime(date("Y-m-d 21:00:00")),
            strtotime(date("Y-m-d 23:00:00")),
            strtotime("+1 day", strtotime(date("Y-m-d 07:00:00")))
        );

        if (time() > strtotime(date("Y-m-d 23:00:00"))) {
            $start = $time_battle[9];
        } elseif ($time_battle[0] < $time && $time < $time_battle[1]) {
            $start = $time_battle[1];
        } elseif ($time > $time_battle[1] && $time < $time_battle[2]) {
            $start = $time_battle[2];
        } elseif ($time > $time_battle[2] && $time < $time_battle[3]) {
            $start = $time_battle[3];
        } elseif ($time > $time_battle[3] && $time < $time_battle[4]) {
            $start = $time_battle[4];
        } elseif ($time > $time_battle[4] && $time < $time_battle[5]) {
            $start = $time_battle[5];
        } elseif ($time > $time_battle[5] && $time < $time_battle[6]) {
            $start = $time_battle[6];
        } elseif ($time > $time_battle[6] && $time < $time_battle[7]) {
            $start = $time_battle[7];
        } elseif ($time > $time_battle[7] && $time < $time_battle[8]) {
            $start = $time_battle[8];
        } else {
            $start = $time_battle[0];
        }
        return $start;
    }

    public function getTeam() {
        $team = mysql_fetch_assoc(mysql_query('SELECT `id_team` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        return $team['id_team'];
    }

    public function targetRefresh() {
        $arr = [];
        $listUser = mysql_query('SELECT `id_user` FROM `avenax_team_battle` WHERE `id_battle` = "' . $this->getIdBattle() . '" AND `fight` = "2" AND `dead` = "0" AND `id_team` != "' . $this->getTeam() . '"');

        while ($row = mysql_fetch_array($listUser)) {
            $arr[$row['id_user']] = $row['id_user'];
        }

        $rand = array_rand($arr);
        mysql_query('UPDATE `avenax_team_battle` SET `target` = "' . $rand . '" WHERE `id_user` = "' . $this->id . '"');

        return $rand;
    }

    public function getTravaOpp($id_opp) {
        $trava_time = mysql_fetch_assoc(mysql_query('SELECT `trava` FROM `avenax_team_battle` WHERE `id_user` = "' . $id_opp . '"'));
        return $trava_time['trava'];
    }

    public function getHealthOpp($id_opp) {
        $health = mysql_fetch_assoc(mysql_query('SELECT `health` FROM `avenax_team_battle` WHERE `id_user` = "' . $id_opp . '"'));
        return $health['health'];
    }

    public function getDeadOpp() {
        if (mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_team_battle` WHERE `fight` = "2" AND `id_user` = "' . $this->target . '" AND `dead` = "0"'), 0) == true) {
            return true;
        }
        return false;
    }

    public function getOpp($id_opp) {
        $opponent = mysql_fetch_assoc(mysql_query('SELECT `id`, `def`, `login`, `max_health` FROM `users` WHERE `id` = "' . $id_opp . '"'));
        return $opponent;
    }

    public function getTarget() {
        $opponent = mysql_fetch_assoc(mysql_query('SELECT `target` FROM `avenax_team_battle` WHERE `id_user` = "' . $this->id . '"'));
        return $this->target = $opponent['target'];
    }

    public function getUserRock($user) {
        mysql_query("UPDATE `users` SET `kamen` = `kamen` - '1' WHERE `id` = '" . $user . "' LIMIT 1");
        mysql_query("UPDATE `avenax_team_battle` SET `kamen` = '" . (time() + 30) . "' WHERE `id_user` = '" . $user . "' LIMIT 1");
    }

    public function getUserGrass($user) {
        mysql_query("UPDATE `users` SET `trava` = `trava` - '1' WHERE `id` = '" . $user . "' LIMIT 1");
        mysql_query("UPDATE `avenax_team_battle` SET `trava` = '" . (time() + 30) . "' WHERE `id_user` = '" . $user . "' LIMIT 1");
    }

    public function attack() {

        $user = $this->UserId();
        $us = $this->id;
        $id_opp = $this->target == true ? $this->target : $this->targetRefresh();
        $id_opp = $this->getDeadOpp() == true ? $this->target : $this->targetRefresh();
        $opponent = $this->getOpp($id_opp);
        # если таргет нету, финал
        if ($user && $opponent) {

            $_def_opp = rand(round($opponent['def'] / 12), round($opponent['def'] / 7));

            $str = 0;
            $str += round(rand(($user['str'] / 6), ($user['str'] / 4)));
            $str_def = 0;

            # + 35%
            if ($this->kamen > time()) {
                $str += ceil($str * 35 / 100);
            }
            # - 35%
            if ($this->getTravaOpp($opponent['id']) > time()) {
                $str_def -= ceil($str * 35 / 100);
            }

            $_str = $str - $_def_opp - $str_def;
            if ($_str < 0) {
                $_str = 0;
            }

            $dmg_time = time() - $this->time_dmg;
            if ($dmg_time < 2) {
                $_str = 0;
            }

            $opp_health = $this->getHealthOpp($opponent['id']);

            $checkHealth = $opp_health - $_str;
            $dead = false;
            if ($checkHealth <= 0) {
                $dead = true;
            }

            mysql_query("INSERT INTO `avenax_team_battle_log` SET `id_user` = '" . $user['id'] . "', `id_opp` = '" . $opponent['id'] . "', `level` = '" . $this->spotLevel() . "', `damage` = '" . $_str . "' " . ($dead ? ", `dead` = '1'" : null) . "");
            mysql_query("UPDATE `avenax_team_battle` SET " . ($dead ? '`health` = "0", `dead` = "1"' : '`health` = `health` - "' . $_str . '"') . " WHERE `id_user` = '" . $opponent['id'] . "'");
            mysql_query("UPDATE `avenax_team_battle` SET `damage` = `damage` + '" . $_str . "', `time_dmg` = '" . time() . "'" . ($dead ? ", `kill` = `kill` + '1'" : null) . " WHERE `id_user` = '" . $user['id'] . "'");
            return true;
        }

        return false;
    }

    public function getLogBattle() {
        $result = mysql_query("SELECT COUNT(*) FROM `avenax_team_battle_log` WHERE `level` = '" . $this->spotLevel() . "'");
        if ($result && mysql_result($result, 0) == true) {
            $query = mysql_query("SELECT `id`, `id_user`, `id_opp`, `dead`, `damage` FROM `avenax_team_battle_log` WHERE `level` = '" . $this->spotLevel() . "' ORDER BY `id` DESC LIMIT 15");
            $arr = [];
            while ($row = mysql_fetch_assoc($query)) {
                $arr[$row['id']] = [];
                $arr[$row['id']]['id_user'] = $row['id_user'];
                $arr[$row['id']]['id_opp'] = $row['id_opp'];
                if ($row['dead'] == true) {
                    $arr[$row['id']]['dead'] = $row['dead'];
                } else {
                    $arr[$row['id']]['damage'] = $row['damage'];
                }
            }
            return $arr;
        }
        return false;
    }

    public function getListUser() {
        $arr = [];
        $user = mysql_query('SELECT `id_user` FROM `avenax_team_battle` WHERE `level` = "' . $this->spotLevel() . '" AND `fight` = "1" LIMIT 20');
        while ($row = mysql_fetch_assoc($user)) {
            $arr[$row['id_user']] = $row['id_user'];
        }
        return $arr;
    }

    public function getCheckStart() {
        $battle = mysql_result(mysql_query("SELECT COUNT(*) FROM `avenax_team` WHERE `level` = '" . $this->spotLevel() . "' AND `fight` = '0'"), 0);
        return $battle;
    }

    public function startFight() {
        $countUserLevel = $this->getCountPlayerLevel();
        $timer = $this->getTime(time());
        $checkTime = $timer - time();

        if ($countUserLevel >= 2 && $countUserLevel <= 20 && $checkTime <= 10) {
            if (!$this->getCheckStart()) {
                $userList = $this->getListUser();
                shuffle($userList);
                mysql_query("INSERT INTO `avenax_team` SET `time_start` = '$timer', `level` = '" . $this->spotLevel() . "', `fight` = '0'");
                $id_battle = mysql_insert_id();
                $li = 0;
                foreach ($userList as $user) {
                    if ($li == 0) {
                        mysql_query('UPDATE `avenax_team_battle` SET `id_team` = "1", `fight` = "2", `id_battle` = "' . $id_battle . '" WHERE `level` = "' . $this->spotLevel() . '" AND `id_user` = "' . $user . '"');
                        $li = 1;
                    } else if ($li == 1) {
                        mysql_query('UPDATE `avenax_team_battle` SET `id_team` = "2", `fight` = "2", `id_battle` = "' . $id_battle . '" WHERE `level` = "' . $this->spotLevel() . '" AND `id_user` = "' . $user . '"');
                        $li = 0;
                    }
                }
            }
            #$this -> getUserIdBattle();
            return true;
        }
        return false;
    }

    public function countFightFinalTeam() {
        $teams = mysql_query('SELECT `id_team` FROM `avenax_team_battle` WHERE `level` = "' . $this->spotLevel() . '" AND `fight` = "2" AND `dead` = "0" AND `id_battle` = "' . $this->getIdBattle() . '"');
        $arr = [];
        while ($team = mysql_fetch_assoc($teams)) {
            $arr[] = $team['id_team'];
        }
        $arr = array_unique($arr);
        return count($arr);
    }

    public function countFightFinalTeamVictory() {
        $teams = mysql_query('SELECT `id_team` FROM `avenax_team_battle` WHERE `level` = "' . $this->spotLevel() . '" AND `fight` = "2" AND `dead` = "0" AND `id_battle` = "' . $this->getIdBattle() . '"');
        $arr = [];
        while ($team = mysql_fetch_array($teams)) {
            $arr[] = $team['id_team'];
        }
        $arr = array_unique($arr);

        if (!empty($arr)) {
            return $arr[0];
        }
        return false;
    }

    public function getIdBattle() {
        $user = $this->UserId();
        return $user['id_battle'];
    }

    public function finalFight() {

        $countPlayer = $this->getCountPlayerBattle();
        $countTeam = $this->countFightFinalTeam();

        if ($countTeam <= 1 || $countPlayer <= 1) {
            if ($this->getCheckStart()) {
                return true;
            }
        }
        return false;
    }

    public function setFinalResult() {

        $end = [];
        $showList = mysql_query('SELECT `id_user`, `damage`, `kill`, `id_team` FROM `avenax_team_battle` WHERE `id_battle` = "' . $this->getIdBattle() . '" ORDER BY `damage` DESC');

        $winTeam = $this->countFightFinalTeamVictory();
        $i = 0;

        if (empty($showList)) {
            return false;
        }

        while ($id = mysql_fetch_assoc($showList)) {
            $i ++;
            if ($i == 1) {
                $up = 50;
            } else if ($i == 2) {
                $up = 40;
            } else if ($i == 3) {
                $up = 30;
            } else {
                $up = 0;
            }
            $end[$i] = [];
            $end[$i]['id_user'] = $id['id_user'];
            $end[$i]['place'] = $i;
            $end[$i]['damage'] = $id['damage'];
            $end[$i]['kill'] = $id['kill'];

            if ($id['id_team'] == $winTeam) {
                $end[$i]['almaz'] = 10 + $up;
            } else {
                $end[$i]['almaz'] = 0;
            }
        }

        foreach ($end as $user) {
            if ($user['almaz']) {
                mysql_query("UPDATE `users` SET `almaz` = `almaz` + " . $user['almaz'] . "  WHERE id = " . $user['id_user'] . " LIMIT 1");
            }
            mysql_query("INSERT INTO `avenax_final_place` SET `id_battle` = '" . $this->getIdBattle() . "', `id_user` = '" . $user['id_user'] . "', `damage` = '" . $user['damage'] . "', `kill` = '" . $user['kill'] . "', `gold` = '" . $user['almaz'] . "'");
        }

        mysql_query('UPDATE `avenax_team` SET `fight` = "1" WHERE `id` = "' . $this->getIdBattle() . '"');
        mysql_query("DELETE FROM `avenax_team_battle` WHERE `id_battle` = '" . $this->getIdBattle() . "'");
        mysql_query("DELETE FROM `avenax_team_battle_log` WHERE `level` = '" . $this->spotLevel() . "'");

        return true;

    }

    public function getResult() {
        $results = mysql_query('SELECT `id_user`, `damage`, `kill`, `gold` FROM `avenax_final_place` WHERE `id_battle` = "' . $this->getIdBattle() . '" ORDER BY `damage` DESC');


        echo '<ul>';
        $i = 0;

        while ($result = mysql_fetch_assoc($results)) {
            $i ++;
            $dmg_user = mysql_fetch_assoc(mysql_query('SELECT `login` FROM `users` WHERE `id` = "' . $result['id_user'] . '"'));


            $quest = mysql_fetch_assoc(mysql_query("SELECT * FROM `quest` WHERE `id` = '525'"));

            $q = mysql_fetch_assoc(mysql_query("SELECT * FROM `quest_user` WHERE `id_quest` = '$quest[id]' AND `id_user` = '" . $this->id . "'"));


            if ($q['last'] < time()) {

                mysql_query("UPDATE `quest_user` SET `koll` = `koll`+'1' WHERE (`id` = '" . $q['id'] . "')");

            }

            echo '<li><font color="#eff0a1"> ' . $i . '.</font> <font color="white">' . $dmg_user['login'] . ': <img width="16px" src="/images/icons/sum_stat.png" alt="*" /> Урон: <font color="red">' . $result['damage'] . '</font>, Убито: <font color="red">' . $result['kill'] . '</font> ' . ($result['gold'] ? ' Награда: <font color="#eff0a1">' . $result['gold'] . '</font> <img src="/images/icons/almaz.png" alt="almaz" />' : null) . '</font></li>';


        }
        echo '</ul><br />';
    }

    public function getResultCheck() {
        $log = mysql_result(mysql_query('SELECT COUNT(*) FROM `avenax_final_place` WHERE `id_battle` = "' . $this->getIdBattle() . '"'), 0);


        return $log;
    }
}

/*
 * Горбунов Александр 
 * https://vk.com/sasha_gorbunov
 * Распространение и перепродажа запрещена
 */