<?php

define("_CONSTANT_", 1);

require_once '../../core/start.php';

checkAuth();

head('Арена', 'Арена');

// Аналог адских игр в мт надо написать.

require_once '../../class/fight/Attack.php';
$Attack = new Attack(); 

$arena = DB::$dbs->queryFetch("SELECT * FROM ". ARENA ." WHERE `id` = ?", [1]);

if ($arena['start'] == 0) 
{
    ?> 

    <div class="head">Бой завершен!</div>
    <div class="headerImg"><img src="<?=HOME?>/img/arena.png" alt="[header-img]" width="350px"></div>
    <div class="wrap"> 

        <?php
        if ($arena['out_users'] == 1) 
        {
            ?> 

                Игроки не принимали участия.

            <?php
        } 
        else 
        {
            ?> 

            Свет набрал: <?=ico('rating-white.png') . $arena['white_rating']?><br/>
            Тьма набрала: <?=ico('rating-dark.png') . $arena['dark_rating']?><br/>
            Победила сторона: <?=($arena['white_rating'] > $arena['dark_rating'] ? '<span style="color: blue;">Свет</span>' : '<span style="color: red;">Тьма</span>')?>

        <?php
        }
        ?>
        <br/><br/>
        До начала боя: <?=ico('clock.png') . countTime($arena['time_start'] - time())?>
    </div>

    <?php
    # Start battle;
    if ($arena['time_start'] <= time() && $arena['start'] == 0) 
    {
        $timeBattle = time() + 1800;  # 30 minutes;
        $botCount   = 50;             # Count bot for insert;  
        $botRating  = rand(1, 10);    # Insert bot rating;
        $botHealth  = rand(10, 100);  # Bot Health;
        $botStrike  = rand(1, 10);    # Bot strike;
        $botDefend  = rand(1, 10);    # Bot defend;

        DB::$dbs->query("UPDATE ". ARENA ." SET `time` = ?, `start` = ?, `end` = ?, `white_rating` = ?, `dark_rating` = ? WHERE `id` = ?", [$timeBattle, 1, 0, 0, 0, 1]);
        
        # Insert bots; - white;
        for ($i = 0; $i < $botCount; ++$i) 
        {
            DB::$dbs->query("INSERT INTO ". ARENA_BOT ." (`strike`, `defend`, `health`, `rating`, `dead`, `side`) VALUES (?, ?, ?, ?, ?, ?)", [rand($botStrike, 15), rand($botDefend, 15), rand($botHealth, 200), rand($botRating, 11), 0, 'white']);
        }

        # Insert bots; - dark;
        for ($i = 0; $i < $botCount; ++$i) 
        {
            DB::$dbs->query("INSERT INTO ". ARENA_BOT ." (`strike`, `defend`, `health`, `rating`, `dead`, `side`) VALUES (?, ?, ?, ?, ?, ?)", [rand($botStrike, 15), rand($botDefend, 15), rand($botHealth, 200), rand($botRating, 11), 0, 'dark']);
        }
        header("Location: ?__". uniqid());
        exit();
    }
} 
else 
{
    # Give reward;
    if ($arena['end'] == 1) 
    {
        $arenaUsersCount = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ". USERS ." WHERE `arena_rating_now` > ?", [0]);
        $arenaUsers      = DB::$dbs->query("SELECT * FROM ". USERS ." WHERE `arena_rating_now` > ?", [0]);

        if (empty($arenaUsersCount)) 
        {
            DB::$dbs->query("UPDATE ". ARENA ." SET `out_users` = ?, `start` = ?, `time_start` = ? WHERE `id` = ?", [1, 0, time() + 600, 1]);
            header("Location: ?");
        } 
        else 
        {
            while ($ank = $arenaUsers -> fetch()) 
            {

                $another = ($ank['side'] == 'white' ? 'dark' : 'white');

                if ($arena[$ank['side'] .'_rating'] > $arena[$another .'_rating']) 
                {
                    if ($ank['vip'] > time()) 
                    {
                        $ank['arena_rating_now'] = ceil($ank['arena_rating_now'] * 2);
                    } 
                    else 
                    {
                        $ank['arena_rating_now'] = $ank['arena_rating_now'];
                    }
                    $journal = 'Сражение на арене завершено! Ваша сторона победила! Вы получили '. ico('gold.png') . $ank['arena_rating_now'] .' золота.';
                    $User->addUserJournal($journal, $ank['id']);
                    DB::$dbs->query("UPDATE ". USERS ." SET `money` = ?, `arena_rating_now` = ? WHERE `id` = ?", [($ank['money'] + $ank['arena_rating_now']), 0, $ank['id']]);
                } 
                else 
                {
                    $ank['arena_rating_now'] = ceil($ank['arena_rating_now'] / 2);
                    $journal = 'Сражение на арене завершено! Ваша сторона проиграла! Вы получили '. ico('exp.png') . $ank['arena_rating_now'] .' опыта.';
                    $User->addUserJournal($journal, $ank['id']);
                    DB::$dbs->query("UPDATE ". USERS ." SET `exp` = ?, `arena_rating_now` = ? WHERE `id` = ?", [($ank['exp'] + $ank['arena_rating_now']), 0, $ank['id']]);
                }

                $Attack->clearLog($user['id']);
            }
            DB::$dbs->query("UPDATE ". ARENA ." SET `out_users` = ?, `start` = ?, `time_start` = ? WHERE `id` = ?", [0, 0, time() + 600, 1]);
            DB::$dbs->query("DELETE FROM ". ARENA_BOT ."");
        }
        header("Location: ?__". uniqid());
        exit();
    } 
    else 
    {
        $botCount = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ". ARENA_BOT ." WHERE `dead` = ?", [0]);

        # End arena battle;
        if (empty($botCount) || $arena['time'] <= time()) 
        {
            DB::$dbs->query("UPDATE ". ARENA ." SET `end` = ? WHERE `id` = ?", [1, 1]);
        } 
        else 
        {
            $enemy = DB::$dbs->queryFetch("SELECT * FROM ". ARENA_BOT ." WHERE `dead` = ? and `side` != ?", [0, $user['side']]);
            # Fight;
            $User->checkHealth('Вы были убиты во время боя!');

            if (isset($_GET['attack'])) 
            {
                if (empty($enemy)) 
                {
                    errorNoExit('Противник не найден');
                } 
                else 
                {
                    $myAttack = $Attack->attackDefend($Attack->attacked($user['strike']), $Attack->defend($enemy['defend']));
         
                    if ($user['max_attack'] < $myAttack) 
                    {
                        DB::$dbs->query("UPDATE " . USERS . " SET `max_attack` = ? WHERE `id` = ?", [$myAttack, $user['id']]);
                    }
                    /**/
                    $npcAttack = $Attack->attackDefend($Attack->attacked($enemy['strike']), $Attack->defend($user['defend']));
                    /**/ 
                    if ($myAttack > $enemy['health']) 
                    {
                        $myAttack = $enemy['health'];
                    } 
                    /**/ 
                    if ($npcAttack > $user['health']) 
                    {
                        $npcAttack = $user['health'];
                    }

                    if ($enemy['health'] > 0 && $myAttack == $enemy['health']) 
                    {
                        DB::$dbs->query("UPDATE ". ARENA_BOT ." SET `dead` = ? WHERE `id` = ?", [1, $enemy['id']]);
                        DB::$dbs->query("UPDATE ". USERS ." SET `health` = ?, `arena_rating_now` = ?, `arena_rating` = ? WHERE `id` = ?", [($user['health'] - $npcAttack), ($user['arena_rating_now'] + $enemy['rating']), ($user['arena_rating'] + $enemy['rating']), $user['id']]);
                        DB::$dbs->query("UPDATE ". ARENA ." SET `".$user['side']."_rating` = ? WHERE `id` = ?", [($arena[$user['side'] . '_rating'] + $enemy['rating']), 1]);
                        $Attack->addLog($user['id'], 2, 'Вы убили противника');
                        $Attack->addLog($user['id'], 2, '<span style="color: red;">Перед смертью противник успел ударить вас на '. $npcAttack .'</span>');
                    } 
                    else if ($enemy['health'] > 0) 
                    {
                        DB::$dbs->query("UPDATE ". ARENA_BOT ." SET `health` = ? WHERE `id` = ?", [($enemy['health'] - $myAttack), $enemy['id']]);
                        DB::$dbs->query("UPDATE ". USERS ." SET `health` = ? WHERE `id` = ?", [($user['health'] - $npcAttack), $user['id']]);
                        $Attack->addLog($user['id'], 2, 'Вы ударили противника на '. $myAttack);
                        $Attack->addLog($user['id'], 2, '<span style="color: red;">Противник ударил вас на '. $npcAttack .'</span>');
                    }
                }

                header("Location: ?__" . uniqid());
            }
            ?> 

            <div class="wrap">
                Свет набрал: <?=ico('rating-white.png') . $arena['white_rating']?><br/>
                Тьма набрала: <?=ico('rating-dark.png') . $arena['dark_rating']?><br/>
                До конца боя: <?=ico('clock.png') . countTime($arena['time'] - time())?><br/>
                <?=ico('strike.png') . $enemy['strike'] . ico('defend.png') . $enemy['defend'] . ico('health.png') . $enemy['health']?>
            </div>
            <a href="<?=HOME?>/modules/arena/index.php?attack" class="link-touch"><?=ico('attack.png')?> Атаковать</a>

            <?php
            $Attack->skillPanel();
            $Attack->bottlePanel();
            $Attack->readLog($user['id'], 2);
            $enemyCount = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ". ARENA_BOT ." WHERE `side` != ? and `dead` = ?", [$user['side'], 0]);
            ?>

            <div class="head">Противники</div>

            <?php 
            if (empty($enemyCount)) 
            {
                ?> 

                <br/>
                <div class="content">
                    Все противники убиты. Ожидайте пока вражеская команда убьет противников или пока закончится время.<br/>
                    <a href="<?=HOME?>/modules/arena/index.php?" class="link-touch">Обновить</a>
                </div>

                <?php
            } 
            ?>
            
            <div class="link-touch">Адская гончая<div class="count">x<?=$enemyCount?></div></div>

            <?php
        }
    }
}

require_once '../../core/foot.php';