<?php

define('_CONSTANT_', 1); 

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

checkAuth();

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

switch ($do) 
{
    default: 
        
        header("Location: ".HOME."/");
        exit(); 
        
        break; 
        
        case 'attack.location.npc': 
            
            head('Бой', 'Бой');
        
            if (isset($_GET['npcId']) && !empty($_GET['npcId']) && isset($_GET['locationId']) && !empty($_GET['locationId'])) 
            { 
                $locationId = $Filter->clearInt($_GET['locationId']);
                $npcId      = $Filter->clearInt($_GET['npcId']);
                
                $location = DB::$dbs->queryFetch("SELECT * FROM " . LOCATION . " WHERE `id` = ?", [$locationId]); 
                $npc      = DB::$dbs->queryFetch("SELECT * FROM " . NPC . " WHERE `id` = ?", [$npcId]);
                
                /*
                 * Если нет такой локации;
                 */
                if (!$location) 
                {
                    error('Локации не существует.', '', 'На главную');
                } 
                
                /*
                 * Если пользователь не на этой локации;
                 */ 
                if ($user['location_id'] != $locationId) 
                {
                    error('Вы не на этой локации.', '', 'На главную');
                }
                
                /*
                 * Если нет такого NPC;
                 */ 
                if (!$npc) 
                {
                    error('Противник не существует.', '', 'На главную');
                }
                
                /*
                 * Если локация npc != полученой локации;
                 */ 
                if ($npc['location_id'] != $locationId) 
                {
                    error('Противник не с этой локации.', '', 'На главную');
                } 
                
                /* 
                 * Если противник мертв;
                 */ 
                if ($npc['dead'] == 1) 
                {
                    error('Противник мертв.', '/game/index.php');
                } 
                
                # Lvl check;
                if ($npc['lvl'] != $user['lvl']) 
                {
                    error('Противник не подходит по уровню.', '/game/index.php');
                }
                
                /* 
                 * Check user health;
                 */ 
                $User->checkHealth('Вы были убиты во время боя!');
                /* 
                /* 
                 * -------------------------------------------------------------
                 * АТАКА
                 * -------------------------------------------------------------
                 */
                if (isset($_GET['attack']) && $npc['dead'] == 0 && $user['health'] > 0) 
                {
                    if ($Attack->checkCooldown($user['id'], 2) == true) 
                    {
                        header("Location: ". $_SERVER['REQUEST_URI']. "?");
                        exit();
                    }

                    # Random gold;
                    $randGoldDrop = rand(1, 100);

                    if ($randGoldDrop <= 2) 
                    {
                        DB::$dbs->query("UPDATE ". USERS ." SET `money` = ? WHERE `id` = ?", [($user['money'] + 1), $user['id']]);
                        $Attack->addLog($user['id'], '<span style="color: #0183FB;">Вы нашли золото '. ico('gold.png').'1</span>');
                    }

                    if ($npc['health'] > 0) 
                    {
                        # Attack mob; 
                        $chanseAttack = rand(1, 100);
                        
                        if ($chanseAttack <= 50) 
                        {
                            $npcAttack = $Attack->attackStart('npc', $user['id'], '', $npc['strike'], '');

                            if ($npcAttack > $user['health']) 
                            {
                                $npcAttack = $user['health'];
                            } 

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

                        $myAttack = $Attack->attackStart('user', $user['id'], '', '', $npc['defend']);

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


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

                        DB::$dbs->query("UPDATE " . NPC . " SET `health` = ? WHERE `id` = ?", [($npc['health'] - $myAttack), $npc['id']]);
                        $Attack->addCooldown($user['id']);
                        header("Location: " . HOME . "/modules/fight/attack.php?do=attack.location.npc&npcId=" . $Filter->clearInt($npc['id']) . "&locationId=" . $locationId . "");
                    } 
                } 
                
                # Dead npc;
                if ($npc['health'] == 0 && $npc['dead'] == 0) 
                { 
                    
                    if (!empty($user['clan_id'])) 
                    {
                        $clanRating = rand(1, $npc['lvl']);
                        DB::$dbs->query("UPDATE ". USERS ." SET `clan_rating` = ? WHERE `id` = ?", [($user['clan_rating'] + $clanRating), $user['id']]);
                    }
                    echo '<div style="margin: 8px;">'.ico('rip.png').' Противник убит!<br/>' . moneyIcon() . ' + ' . $Filter->clearInt($npc['money']) . (!empty($user['clan_id']) ? '<br/>'. ico('clan-rating.png') .' + '. $clanRating : null) .'</div>'; 
                    
                    DB::$dbs->query("UPDATE " . NPC . " SET `dead_time` = ?, `health` = ? WHERE `id` = ?", [time(), $npc['max_health'], $npc['id']]);
                    DB::$dbs->query("UPDATE " . USERS . " SET `money` = ? WHERE `id` = ?", [($user['money'] + $Filter->clearInt($npc['money'])), $user['id']]); 
                    # Add message in journal;
                    $journal = 'Вы убили противника "' . $Filter->output($npc['name']) . '" на локации ' . $Filter->output($location['name']) . '. <br/>' . moneyIcon() . ' + ' . $Filter->clearInt($npc['money']) . (!empty($user['clan_id']) ? '<br/>'. ico('clan-rating.png') .' + '. $clanRating : null);
                    $User->addUserJournal($journal, $user['id']);
                    $Attack->clearLog($user['id']);
                    
                    echo '<a href="' . HOME . '/modules/fight/location.php?locationId='. $locationId .'" class="link-touch"> Завершить бой</a>';
                } 
                else 
                {
                    $npcHealth = round($npc['health'] / $npc['max_health'] * 100,2);
                    
                    echo '<div style="text-align: center;"><img src="/img/NPC/'.$Filter->output($npc['img']).'" alt="[npc-img]" width="70px" height="70px"><br/>' . $Filter->output($npc['name']) . '</div> <br/> <div class="npcHealth"><div class="npcHealthLine" style="width: ' . $npcHealth . '%;"></div></div>';
                    echo ico('strike.png'), $npc['strike'], ico('defend.png'), $npc['defend'], ico('health.png'), $npc['health'], '/', $npc['max_health'], '<br/>';
                    echo '<a href="' . HOME . '/modules/fight/attack.php?do=attack.location.npc&amp;npcId=' . $Filter->clearInt($npc['id']) . '&amp;locationId=' . $locationId . '&amp;attack" class="link-touch">'.ico('attack.png').' Атаковать</a>';
                    $Attack->skillPanel();
                    $Attack->bottlePanel();
                    $Attack->readLog($user['id']);
                }
            } 
            else 
            { 
                error('Не получен идентификатор врага и/или локации.', '/modules/fight/location.php', 'Локации');
            } 
            break;
} 

/*
 * Connect footer;
 */
require_once '../../core/foot.php';