<?php
define('ROOT', dirname(__DIR__));
require_once(ROOT . '/system/func.php');
auth();
$title = 'Вторжение';
error_reporting(0);

include_once ROOT . '/system/head.php';
include_once(ROOT . '/system/header.php');
include_once ROOT . '/invasion/Invasion.php';
$needLevel = 5;
if ($user['level'] < $needLevel) {
    $_SESSION['msg'] = 'Доступно с ' . $needLevel . ' уровня';
    Invasion::redirect('/');
}

$btlPrepared = Invasion::getPrepare();
$btlBattled = Invasion::getBattled();
$btlResulted = Invasion::getResulted();

if ($btlPrepared == 0 && $btlBattled == 0 && $btlResulted == 0) {
    if ((int)date("H", time()) >= 0 && (int)date("H", time()) < 6) {
        $btlTime = mktime(6, 0, 0);
    } elseif ((int)date("H", time()) >= 6 && (int)date("H", time()) < 10) {
        $btlTime = mktime(10, 0, 0);
    } elseif ((int)date("H", time()) >= 10 && (int)date("H", time()) < 14) {
        $btlTime = mktime(14, 0, 0);
    } elseif ((int)date("H", time()) >= 14 && (int)date("H", time()) < 18) {
        $btlTime = mktime(18, 0, 0);
    } elseif ((int)date("H", time()) >= 18 && (int)date("H", time()) < 22) {
        $btlTime = mktime(22, 0, 0);
    } else {
        $btlTime = mktime(0, 0, 0) + 86400;
    }
    //echo "<img src='/images/1234.png'> </a></div>";
    echo '<div style="text-align: center;" class="header center">До начала ' . tl($btlTime - time()) . '</div>';
}

$ability = mysql_query("SELECT * FROM `ability` WHERE `id_user` = '" . $user['id'] . "' ORDER BY `id` LIMIT 1");
$ability = mysql_fetch_array($ability);

if (Invasion::getCountPrepare() == true) {
    $btl = $btlPrepared;
    echo '<div style="text-align: center;" class="header center">До начала ' . (($btl['starttime'] - time() <= 0) ? '0 c.' : tl($btl['starttime'] - time())) . '</div>';

   // echo "<img src='/images/1234.png'> </a></div>";

    $myPlayer = Invasion::getMyBattlePrepare($user['id'], $btl['id']);
    $players = Invasion::getUserBattlePrepare($btl['id']);

    if (filter_has_var(INPUT_GET, 'enter')) {

        if ($myPlayer > 0) {
            $_SESSION['msg'] = 'Вы записаны в бой!';
            Invasion::redirect('?');
        }
        mysql_query("INSERT INTO `demons_players` (`battle`,`id_user`,`health`,`damage`) VALUES ('" . $btl['id'] . "', '" . $user['id'] . "', '" . $user['max_health'] . "', '0')");
        $_SESSION['msg'] = 'Вы успешно записались в бой!';
        Invasion::redirect('?');
    }

    if ($myPlayer == 0) {
        echo '<div class="header center" style="text-align: center;"><div class="btn_grey"><span class="cb_end"><span class="cb_ttl"><a href="?enter">Записаться в бой</a></span></span></div></div>';
    } else {
        echo '<div class="header center" style="text-align: center;">Игроков записано: ' . $players . '</div>';
    }
} elseif (Invasion::getCountPrepare() == false && Invasion::getCountBattled() == true && Invasion::getUserCheck($user['id']) == true) {
    $myBattle = Invasion::getMyBattle($user['id']);
    if ($myBattle['health'] == false) {
        $_SESSION['msg'] = 'Вы были убиты в бою!';
        Invasion::redirect('/cel.php');
    }
    $btl = $btlBattled;
    $mobs = Invasion::getStage($btl['stage']);


    if (mysql_result(mysql_query("SELECT COUNT(*) FROM `demons_players` WHERE `id_user` = '" . $user['id'] . "' AND `battle` = '" . $btl['id'] . "'"), 0) == true) {

        if (filter_has_var(INPUT_GET, 'attack')) {

            // Если часто бьёшь
            if ($myBattle['time_dmg'] > time()) {
                $_SESSION['msg'] = 'Вы промахнулись';
                Invasion::redirect('?');
            }

            if ($btl['status'] == 'end') {
                $_SESSION['msg'] = 'Бой закончился. Награда будет зачислена автоматически!';
                Invasion::redirect('?');
            }

            mysql_query("UPDATE `ability` SET `energy` = '" . ($ability['energy'] + 1) . "' WHERE (`id_user` = '" . $user['id'] . "')");

            $healthBase = 'health';
            if (in_array($btl['stage'], ['mob1', 'mob2', 'mob3'])) {
                $healthBase = 'mob_health';
            }

            $dmg = Invasion::getMyDamage($ability, $user, $mobs);

            if ($dmg >= $btl[$healthBase]) {

                // Конец
                if ($btl['stage'] == 'boss') {
                    mysql_query("UPDATE `demons_battles` SET `status` = 'end'");
                    $_SESSION['msg'] = 'Бой закончился. Награда будет зачислена автоматически!';
                    Invasion::redirect('?');
                } else {
                    if ($btl['stage'] == 'mob1') {
                        mysql_query("UPDATE `demons_battles` SET `stage` = 'mob2', `mob_health` = '" . $btl['mob_max_health'] . "'");
                    } else if ($btl['stage'] == 'mob2') {
                        mysql_query("UPDATE `demons_battles` SET `stage` = 'mob3', `mob_health` = '" . $btl['mob_max_health'] . "'");
                    } else if ($btl['stage'] == 'mob3') {
                        mysql_query("UPDATE `demons_battles` SET `stage` = 'boss'");
                    }
                }
            } else {
                Invasion::getAttackStr($ability, $user, $btl['stage'], $healthBase);
            }
            Invasion::redirect('?');
        }

        // Умения  Сила жизни
        if (isset($_GET['UseSpellHp']) && $ability['statusHp'] == 0 && $ability['energy'] >= 1) {
            // Если юзали и меньше энергии
            if ($ability['statusHp'] == 1 and $ability['energy'] <= 1) {
                header('Location: ?');
                exit();

            }


            $SpellRespHp = ceil($ability['spellHpResp'] + ($user['max_health'] / 100 * 10));

            $logSpellHp = color('lime') . ' Вы полечились  на  ' . ico('ability', 'spell_health.png') . ' ' . $SpellRespHp . ' здоровья </font>';
            $_SESSION['spell'] = $logSpellHp;
            mysql_query("update `demons_players` set `health` = `health` + '" . $SpellRespHp . "' where (`id_user` = '" . $user['id'] . "')");
            mysql_query("update `ability` set `energy` = '" . ($ability['energy'] - 1) . "'  ,  `statusHp` = '1'   where (`id_user` = '" . $user['id'] . "')");
            header('Location: ?');
            exit();

        } else if (isset($_GET['UseSpellDef']) && $ability['statusDef'] == 0 && $ability['energy'] >= 1) { //Умения  Крепкая броня
            //Если юзали и меньше энергии
            if ($ability['statusDef'] == 1 and $ability['energy'] <= 1) {
                header('Location: ?');
                exit();
            }
            $spellDef = ceil($ability['spellDefAbsorb'] + ($user['def'] / 20));

            $logSpellDef = color('lime') . ' Вы уменьшили урон на ' . ico('ability', 'spell_defence.png') . ' ' . $spellDef . ' урона </font>';
            $_SESSION['spell'] = $logSpellDef;
            mysql_query("update `ability` set `energy` = '" . ($ability['energy'] - 1) . "'  ,  `statusDef` = '1'   where (`id_user` = '" . $user['id'] . "')");
            header('Location: ?');
            exit();
        } else if (isset($_GET['UseSpellStr']) and $ability['statusStr'] == 0 and $ability['energy'] >= 1) { //Умения  Сила удара
            // Если юзали и меньше энергии
            if ($ability['statusStr'] == 1 and $ability['energy'] <= 1) {
                header('Location: ?');
                exit();
            }
            $spellStr = ceil($ability['spellStrDmg'] + ($user['str'] / 15));

            $logSpellStr = color('orange') . ' Вы увеличили урон   на  ' . ico('ability', 'double_attack.jpg') . ' ' . $spellStr . '  </font>';
            $_SESSION['spell'] = $logSpellStr;
            mysql_query("update `ability` set   `energy` = '" . ($ability['energy'] - 1) . "'  ,  `statusStr` = '1'   where (`id_user` = '" . $user['id'] . "')");
            header('Location: ?');
            exit();
        }


        // Логи
        if (isset($_SESSION['log'])) {
            echo '<div class="text_p1" style="text-align: center;">';
            echo $_SESSION['log'];
            echo '</div>';
            unset($_SESSION['log']);
        }

        if (isset($_SESSION['spell'])) {
            echo '<div class="text_p1" style="text-align: center;">';
            echo $_SESSION['spell'];
            echo '</div>';
            unset($_SESSION['spell']);
        }

        include_once ROOT . '/invasion/mobBattle.php';
        exit();
    }
} else if ($btlResulted == true) {
    echo '<div class="header center">Бой закончился. Награда будет зачислена автоматически!</div>';
} else if ($btlBattled == true && mysql_result(mysql_query("SELECT COUNT(*) FROM `demons_players` WHERE `id_user` = '" . $user['id'] . "' AND `battle` = '" . $btl['id'] . "'"), 0) == false) {
    echo '<div class="header center" style="text-align: center;"></div>';
}

?>
    <img src='/images/1234.png'> </a></div>

    <div class="wrapper center" style="text-align: center;">Вторжение начинается в 6, 10, 14, 18, 22 часов по игровому времени.</br>
        В начале вам предстоит битва против помощников демона. </br>
        Следующая стадия - это битва против самого демона.</br>
        Стать в очередь, можно за 10 минут, до начала боя!
    </div>


    </div>
    </div>
<?php
require_once(ROOT . '/system/footer.php');
