<?php

define('_CONSTANT_', 1);

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

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

head('Событие | Всадник апокалипсиса', 'Событие | Всадник апокалипсиса');

checkAuth();

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

if (empty($boss)) 
{
    DB::$dbs->query("INSERT INTO ". EVENT_HORSEMAN ." (`id`) VALUES (?)", [1]);
}

# If battle not start;
if ($boss['start'] == 0) 
{
    ?> 
    <div class="headerImg">
        <img src="/img/NPC/horseman.png" width="240px" alt="horseman">
    </div>
    <div class="wrap">
        Бойтесь же смертные. Всадник апокалипсиса идет за вами. Осталось совсем немного...
    </div>
    <?php
} 
else 
{
    if ($boss['time_left'] > time()) 
    {
        # Give reward if boss dead;
        if ($boss['health'] == 0) 
        {
            $usersCount = DB::$dbs->query("SELECT COUNT(`id`) FROM ". EVENT_HORSEMAN_LOG ."");
            
            if (!empty($usersCount)) 
            {
                $usersAll = DB::$dbs->query("SELECT * FROM ". EVENT_HORSEMAN_LOG ."");

                while ($ank = $usersAll -> fetch()) 
                {
                    if ($ank['uron'] > 20000) 
                    {
                        $us = DB::$dbs->queryFetch("SELECT * FROM ". USERS ." WHERE `id` = ?", [$ank['user_id']]);
                        DB::$dbs->query("UPDATE ". USERS ." SET `money` = ?, `exp` = ? WHERE `id` = ?", [($us['money'] + 2000), ($us['exp'] + 2000), $us['id']]);
                        $User->addUserJournal('За победу над Всадником Апокалипсиса вы получаете <span style="color: green;">+'. ico('gold.png').'2000</span>, <span style="color: green;">+'. ico('exp.png').'2000</span>', $us['id']);
                    }
                }
            }

            DB::$dbs->query("UPDATE ". EVENT_HORSEMAN ." SET `start` = ?, `time_start` = ? WHERE `id` = ?", [0, (time() + 14400), 1]);
            DB::$dbs->query("TRUNCATE ". EVENT_HORSEMAN_LOG ."");
            header("Location: ?");
            exit();
        } 
        else 
        {
            $User->checkHealth('Вы были убиты во время боя!');

            if (isset($_GET['attack'])) 
            {
                if ($Attack->checkCooldown($user['id'], 2) == true) 
                {
                    header("Location: ". $_SERVER['REQUEST_URI']. "?");
                    exit();
                }

                #$myAttack  = $Attack->attackDefend($Attack->attacked($user['strike'], $user['id']), $Attack->defend($boss['defend']), $user['id']);
                $myAttack = $Attack->attackStart('user', $user['id'], '', '', $boss['defend']);

                if ($user['max_attack'] < $myAttack) 
                {
                    DB::$dbs->query("UPDATE " . USERS . " SET `max_attack` = ? WHERE `id` = ?", [$myAttack, $user['id']]);
                }

                if ($myAttack > $boss['health']) 
                {
                    $myAttack = $boss['health'];
                } 

                if ($boss['health'] > 0) 
                {
                    $bossAttack = rand(1, 100);

                    if ($bossAttack < 40) 
                    {
                        #$npcAttack = $Attack->attackDefend($Attack->attacked($boss['strike']), $Attack->defend($user['defend']));
                        $npcAttack = $Attack->attackStart('npc', $user['id'], '', $boss['strike'], '');

                        if ($npcAttack > $user['health']) 
                        {
                            $npcAttack = $user['health'];
                        }
                        
                        DB::$dbs->query("UPDATE " . USERS . " SET `health` = ? WHERE `id` = ?", [($user['health'] - $npcAttack), $user['id']]); 
                    }

                    $bossCrit = rand(1, 100);

                    if ($bossCrit < 5) 
                    {
                        if (20000 > $user['health']) 
                        {
                            $critBossAttack = $user['health'];
                        } 
                        else 
                        {
                            $critBossAttack = 20000;
                        }

                        DB::$dbs->query("UPDATE " . USERS . " SET `health` = ? WHERE `id` = ?", [($user['health'] - $critBossAttack), $user['id']]); 
                        $Attack->addLog($user['id'], '<span style="color: #FF3333;">Всадник взывает о помощи к богам. Вы теряете (! -'. $critBossAttack .')хп</span>');
                    }

                    DB::$dbs->query("UPDATE " . EVENT_HORSEMAN . " SET `health` = ? WHERE `id` = ?", [($boss['health'] - $myAttack), 1]);
                    $Attack->addCooldown($user['id']);

                    # Horseman log;
                    $check = DB::$dbs->queryFetch("SELECT * FROM ". EVENT_HORSEMAN_LOG ." WHERE `user_id` = ?", [$user['id']]);
                    
                    if (empty($check)) 
                    {
                        DB::$dbs->query("INSERT INTO ". EVENT_HORSEMAN_LOG ." (`user_id`, `uron`) VALUES (?, ?)", [$user['id'], $myAttack]);
                    } 
                    else 
                    {
                        DB::$dbs->query("UPDATE ". EVENT_HORSEMAN_LOG ." SET `uron` = ? WHERE `id` = ?", [$check['uron'] + $myAttack, $check['id']]);
                    }
                } 
                header("Location: ?__". uniqid());
            }

            $npcHealth = round($boss['health'] / $boss['max_health'] * 100,2);
            $userUron  = DB::$dbs->queryFetch("SELECT * FROM ". EVENT_HORSEMAN_LOG ." WHERE `user_id` = ?", [$user['id']]);
            $inFight   = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ". USERS ." WHERE `where` = ?", ['Событие | Всадник апокалипсиса']);
            $bossWord  = ['Я сокрушу вас всех', 'Пощады не будет'];
            shuffle($bossWord);
            ?>
            <div style="text-align: center;">
                <img src="/img/NPC/horseman.png" alt="[npc-img]" width="240px">
                <br/>
                Всадник Апокалипсиса
                <div class="wrap">
                    <?=$bossWord[0]?>
                </div>
            </div> 
            <br/> 
            <?=ico('health.png') . $boss['health']?>/<?=$boss['max_health']?>
            <div class="npcHealth">
                <div class="npcHealthLine" style="width: <?=$npcHealth?>%;">
                </div>
            </div>
            <?=$npcHealth?>%<br/>
            <a href="<?=HOME?>/modules/event/HorsemanOfTheApocalypse.php?attack" class="link-touch"><?=ico('attack.png')?> Атаковать</a>
            <?=$Attack->skillPanel()?>
            <?=$Attack->bottlePanel()?>
            <?=$Attack->readLog($user['id'])?>
            <div class="wrap">
                До конца: <?=countTime($boss['time_left'] - time())?><br/>
                Вы нанесли: <?=(!empty($userUron) ? $userUron['uron'] : 0)?>/20000 урона.<br/>
                В бою: <?=$inFight?>
            </div>
            <?php
        }
    } 
    else 
    {
        DB::$dbs->query("UPDATE ". EVENT_HORSEMAN ." SET `start` = ?, `time_start` = ? WHERE `id` = ?", [0, (time() + 14400), 1]);
        DB::$dbs->query("TRUNCATE ". EVENT_HORSEMAN_LOG ."");
        header("Location: ?");
        exit();
    }
}

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