<?php

define('_CONSTANT_', 1);

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

checkAuth();

head('Заброшеная деревня', 'Заброшеная деревня');

if (empty($user['party'])) 
{
    error('Вы не состоите в банде для похода в это подземелье', '/', 'На главную');
} 

$party = DB::$dbs->queryFetch("SELECT * FROM " . PARTY . " WHERE `id` = ?", [$user['party']]);

if ($party['dungeon_id'] != 1) 
{
    error('Банда создана для похода в другое подземелье', '/', 'На главную');
} 

$fight = DB::$dbs->queryFetch("SELECT * FROM " . DUNGEON_FIGHT . " WHERE `id` = ?", [$user['fight_id']]);

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

# Fight step; 
# Can use as basic shablon on dungeons;
if ($fight['step'] == 1)  
{
    /* 
     * Create NPC;
     */
    if ($fight['npc_add'] == 0) 
    {
        for ($i = 0; $i < 2; $i++) 
        {
            DB::$dbs->query("INSERT INTO " . DUNGEON_NPC . " (`name`, `strike`, `health`, `defend`, `fight_id`) VALUES (?, ?, ?, ?, ?)", ['Волк', 5, 50, 20, $fight['id']]);
        }
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `npc_add` = ? WHERE `id` = ?", [1, $fight['id']]);
        header("Location: ?");
    } 
    /* 
     * END create NPC;
     */
     $checkEnemy = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ?", [$fight['id'], 1]); 
     
     if ($checkEnemy == 2) 
     {
         DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `step` = ?, `npc_add` = ? WHERE `id` = ?", [2, 0, $fight['id']]);
         DB::$dbs->query("DELETE FROM " . DUNGEON_NPC . " WHERE `fight_id` = ?", [$fight['id']]);
     }

     $outputText = 'Вы входите в заброшеную деревню. Впереди вы видите двух волков. В бой!';
} 
else if ($fight['step'] == 2) 
{
    if ($fight['npc_add'] == 0) 
    {
        DB::$dbs->query("INSERT INTO " . DUNGEON_NPC . " (`name`, `strike`, `health`, `defend`, `fight_id`) VALUES (?, ?, ?, ?, ?)", ['Осколок души мага', 10, 1000, 50, $fight['id']]);
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `npc_add` = ? WHERE `id` = ?", [1, $fight['id']]);
        header("Location: ?");
    }

    $checkEnemy = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ?", [$fight['id'], 1]);

    if ($checkEnemy == 1) 
    {
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `step` = ?, `npc_add` = ? WHERE `id` = ?", [3, 0, $fight['id']]);
        DB::$dbs->query("DELETE FROM " . DUNGEON_NPC . " WHERE `fight_id` = ?", [$fight['id']]);
    }

    $outputText = 'Перед собой вы видите Осколок души некогда могущего мага. Необходимо уничтожить его, пока он не уничтожил вас!';
}
else if ($fight['step'] == 3) 
{
    if ($fight['npc_add'] == 0) 
    {
        for ($i = 0; $i < 5; $i++) 
        {
            DB::$dbs->query("INSERT INTO " . DUNGEON_NPC . " (`name`, `strike`, `health`, `defend`, `fight_id`) VALUES (?, ?, ?, ?, ?)", ['Оборотень', 10, 100, 10, $fight['id']]);
        }
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `npc_add` = ? WHERE `id` = ?", [1, $fight['id']]);
        header("Location: ?");
    }

    $checkEnemy = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ?", [$fight['id'], 1]);

    if ($checkEnemy == 5) 
    {
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `step` = ?, `end` = ? WHERE `id` = ?", [3, 1, $fight['id']]);
        DB::$dbs->query("DELETE FROM " . DUNGEON_NPC . " WHERE `fight_id` = ?", [$fight['id']]);
    } 

    if ($fight['end'] == 1 && $fight['reward'] == 0) 
    {
        $partyUsers = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . USERS . " WHERE `party` = ?", [$user['party']]);
        $sql = DB::$dbs->query("SELECT * FROM ".USERS." WHERE `party` = ? ORDER BY `id` DESC LIMIT 10", [$user['party']]);

        $money = ceil(50 / $partyUsers);
        $exp = ceil(100 / $partyUsers);

        # Journal text;
        $journal = 'Вы прошли подземелье Заброшеная деревня. <br/>' . moneyIcon() . ' + ' . $Filter->clearInt($money) . '<br/>' . ico('exp.png') . ' + ' . $Filter->clearInt($exp);

        while ($query = $sql -> fetch()) 
        {
            DB::$dbs->query("UPDATE " . USERS . " SET `money` = ?, `exp` = ? WHERE `id` = ?", [($query['money'] + $money), ($query['exp'] + $exp), $query['id']]);
            $User->addUserJournal($journal, $query['id']);
        }
        DB::$dbs->query("UPDATE " . DUNGEON_FIGHT . " SET `reward` = ? WHERE `id` = ?", [1, $fight['id']]);
        header("Location: ?");
    } 
    else if ($fight['end'] == 1 && $fight['reward'] == 1) 
    {
        /* 
         * End dungeon fight;
         */
         $sql = DB::$dbs->query("SELECT * FROM ".USERS." WHERE `party` = ? ORDER BY `id` DESC LIMIT 10", [$user['party']]);

         while ($ank = $sql -> fetch()) 
         {
             DB::$dbs->query("UPDATE " . USERS . " SET `dungeon_id` = ?, `dungeon_cooldown` = ? WHERE `id` = ?", [0, (time() + 3600), $ank['id']]);
         }
         
         /*if (!empty($party)) 
         {
             DB::$dbs->query("DELETE FROM " . PARTY . " WHERE `id` = ?", [$user['party']]);
         }
         success('Вы прошли подземелье в составе этой банды. Снова отправиться в подземелье вы сможете через час.', '/', 'На главную');
         */
         ?>
        <div class="head">Поздравляем!</div>
        <div class="content">
        Вы прошли подземелье в составе этой банды. Снова отправиться в подземелье вы сможете через час.<br/>
        <?=ico('info.png')?> Для того чтобы тайм аут в подземелье начал сбрасываться - покиньте банду!<br/>
        <?=moneyIcon()?> Золото: + 50 на банду<br/>
        <?=ico('exp.png')?> Опыт: + 100 на банду<br/>
        </div>
        <?php
        require_once '../../../core/foot.php';
        exit();
    }

    $outputText = 'Осталось совсем немного. Необходимо убить оборотней!';
}

/* 
 * Fight; 
 */
 $User->checkHealth('Вы были убиты во время боя!');

 if (isset($_GET['attack'])) 
 {
     $enemy = DB::$dbs->queryFetch("SELECT * FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ?", [$fight['id'], 0]);

     if (empty($enemy)) 
     {
         errorNoExit('Противник не найден');
     } 
     else 
     {
         $myAttack = $Attack->attackDefend($Attack->attacked($user['strike']), $Attack->defend($enemy['defend']));
         $_SESSION['attackUser'] = $myAttack;
         
         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']));
         $_SESSION['attackNpc'] = $npcAttack;
         /**/ 
         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 " . DUNGEON_NPC . " SET `health` = ?, `dead` = ? WHERE `id` = ?", [0, 1, $enemy['id']]);
             DB::$dbs->query("UPDATE " . USERS . " SET `health` = ? WHERE `id` = ?", [($user['health'] - $npcAttack), $user['id']]);
             DB::$dbs->query("INSERT INTO " . DUNGEON_LOG . " (`text`, `time`, `fight_id`) VALUES (?, ?, ?)", [$user['login'] . ' убил ' . $enemy['name'], time(), $fight['id']]);
             DB::$dbs->query("INSERT INTO " . DUNGEON_LOG . " (`text`, `time`, `fight_id`) VALUES (?, ?, ?)", [$enemy['name'] . ' ударил ' . $user['login'] . ' на ' . $npcAttack, time(), $fight['id']]);
             /*DB::$dbs->query("INSERT INTO " . DUNGEON_LOG . " (`text`, `time`, `fight_id`) VALUES (?, ?, ?)", [$enemy['name'] . ' убил ' . $user['login'], time(), $fight['id']]);*/
         } 
         else if ($enemy['health'] > 0) 
         {
             DB::$dbs->query("UPDATE " . DUNGEON_NPC . " SET `health` = ? WHERE `id` = ?", [($enemy['health'] - $myAttack), $enemy['id']]);
             DB::$dbs->query("UPDATE " . USERS . " SET `health` = ? WHERE `id` = ?", [($user['health'] - $npcAttack), $user['id']]);
             DB::$dbs->query("INSERT INTO " . DUNGEON_LOG . " (`text`, `time`, `fight_id`) VALUES (?, ?, ?)", [$user['login'] . ' ударил ' . $enemy['name'] . ' на ' . $myAttack, time(), $fight['id']]);
             DB::$dbs->query("INSERT INTO " . DUNGEON_LOG . " (`text`, `time`, `fight_id`) VALUES (?, ?, ?)", [$enemy['name'] . ' ударил ' . $user['login'] . ' на ' . $npcAttack, time(), $fight['id']]);
         } 
         
         header("Location: ?__" . uniqid());
     }
 } 

 ?> 
 <?=($fight['step'] == 2 ? '<div class="headerImg"><img src="/img/dungeons/1/boss.png" alt="[header-img]" width="50px"></div>' : '<div class="headerImg"><img src="/img/dungeons/1/main.png" alt="[header-img]" width="350px"></div>')?>
 <div class="content"><?=$outputText?></div> 
 <a href="<?=HOME?>/modules/dungeons/1/index.php?attack" class="link-touch"><?=ico('attack.png')?> Атаковать</a>
 <?php 
 $Attack->skillPanel();

 $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ?", [$fight['id'], 0]);
 $n = new Navigator($all,10,'');
 $sql = DB::$dbs->query("SELECT * FROM " . DUNGEON_NPC . " WHERE `fight_id` = ? and `dead` = ? ORDER BY `health` DESC LIMIT {$n->start()}, 10", [$fight['id'], 0]);
?>
<div class="head">Противники</div>
<?php
 while ($npc = $sql -> fetch()) 
 {
     ?>
     <?=ico('skull.png') . $Filter->output($npc['name'])?>: <?=ico('health.png') . $Filter->clearInt($npc['health'])?><br/> 
     <?
 } 
 ?> 
 <div class="head">Лог боя</div>
 <?php
 $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM " . DUNGEON_LOG . " WHERE `fight_id` = ?", [$fight['id']]);
 $n = new Navigator($all,10,'');
 $sql = DB::$dbs->query("SELECT * FROM " . DUNGEON_LOG . " WHERE `fight_id` = ? ORDER BY `time` DESC LIMIT {$n->start()}, 10", [$fight['id']]); 

 while ($string = $sql -> fetch()) 
 {
     ?>
     <?=ico('sword.png') . $Filter->output($string['text'])?> <span style="color: #404040;">[<?=ico('clock.png') . dataTime($string['time'])?>]</span><br/>
     <?php
 }
 ?> 
 <hr>
 <?php

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