<?php

/*
 * Класс для работы с атакой;
 * 
 */
class Attack 
{
    function attackStart($type, $userId = null, $opponentId = null, $npcStrike = null, $npcDefend = null) 
    {
        global $Filter;

        $userId     = (!empty($userId) ? $Filter->clearInt($userId) : null);
        $opponentId = (!empty($opponentId) ? $Filter->clearInt($opponentId) : null);
        $npcStrike  = (!empty($npcStrike) ? $Filter->clearInt($npcStrike) : null);
        $npcDefend  = (!empty($npcDefend) ? $Filter->clearInt($npcDefend) : null);

        # If type = user attack;
        if ($type == 'user') 
        {
            if (empty($userId)) 
            {
                exit('Ошибка. Не получен параметр: Id');
            } 
            else 
            {
                $ank = DB::$dbs->queryFetch("SELECT * FROM ". USERS ." WHERE `id` = ?", [$userId]);

                # Consider user param;
                $attackStrike = round($ank['strike'] * 5 / 100);
                $randAttack   = rand($ank['strike'] - $attackStrike, $ank['strike'] + $attackStrike);

                # Consider other param;
                if ($ank['cooldown'] + 7 <= time()) 
                {
                    $randAttack = ceil($randAttack * 1.5);
                } 
                else 
                {
                    $randAttack = ceil($randAttack / 1.5);
                }

                $userCrit     = round($ank['lvl'] / 3.75);
                $userCritRand = rand(1, 100);

                if ($userCritRand <= $userCrit) 
                {
                    $randAttack     = ceil($randAttack * 1.5);
                    $userCritAttack = 1;
                }

                # Consider opponet param;
                if (!empty($opponentId)) 
                {
                    $opponent = DB::$dbs->queryFetch("SELECT * FROM ". USERS ." WHERE `id` = ?", [$opponentId]);

                    $defendPercent = $Filter->clearInt(round($opponent['defend'] * 5 / 100));
                    $defend        = rand($opponent['defend'] - $defendPercent, $opponent['defend'] + $defendPercent);

                    if ($defend >= $randAttack) 
                    {
                        $return  = round($randAttack * 5 / 100);
                    }  
                    else  
                    {
                        $return = ceil($randAttack - $randDefend);
                    } 
                } 
                else if (!empty($npcDefend))
                {
                    $defendPercent = $Filter->clearInt(round($npcDefend * 5 / 100));
                    $defend        = rand($npcDefend - $defendPercent, $npcDefend + $defendPercent);

                    if ($defend >= $randAttack) 
                    {
                        #$return  = round($randAttack * 5 / 100);

                        if (round($randAttack * 5 / 100) == 0) 
                        {
                            $return = $randAttack;
                        } 
                        else 
                        {
                            $return = round($randAttack * 5 / 100);
                        }
                    }  
                    else  
                    {
                        $return = ceil($randAttack - $randDefend);
                    } 
                } 
                else 
                {
                    $return = 0;
                    exit('Ошибка. Не получен параметр: Id');
                }

                # Exp update;
                $giveExp = ($return > 0 ? round($return / 2) : 1);
                DB::$dbs->query("UPDATE ". USERS ." SET `exp` = ? WHERE `id` = ?", [($ank['exp'] + $giveExp), $ank['id']]);

                $randAttackWord = ['порезали', 'атаковали', 'пнули'];
                shuffle($randAttackWord);

                $this->addLog($userId, 'Вы '. $randAttackWord[0] .' противника на '. $return .' урона '. ($userCritAttack == 1 ? '<span style="color: #FF3333;">(крит)</span>' : null));
                return $return;
            }
        } 
        else if ($type == 'npc') 
        {
            if (empty($userId) or empty($npcStrike)) 
            {
                exit('Ошибка. Не получены параметры: strike, id');
            } 
            else 
            {
                $ank = DB::$dbs->queryFetch("SELECT * FROM ". USERS ." WHERE `id` = ?", [$userId]);

                # Consider npc param;
                $attackStrike = round($npcStrike * 5 / 100);
                $randAttack   = rand($npcStrike - $attackStrike, $npcStrike + $attackStrike);

                $defendPercent = $Filter->clearInt(round($ank['defend'] * 5 / 100));
                $defend        = rand($ank['defend'] - $defendPercent, $ank['defend'] + $defendPercent);

                if ($defend >= $randAttack) 
                {
                    $return  = round($randAttack * 5 / 100);
                }  
                else  
                {
                    $return = ceil($randAttack - $randDefend);
                }

                $randAttackWord = ['порезал', 'атаковал', 'пнул'];
                shuffle($randAttackWord);

                $this->addLog($userId, '<span style="color: #FF3333;">Противник '. $randAttackWord[0] .' вас на '. $return .' урона </span>');
                return $return;
            }
        }
    }

    function deleteSkillId ($str, $id) 
    {
        $filter = '&useSkill='.$id.'';
        $str = str_replace($filter, '', $str);
        return $str;
    }

    function useSkill ($id) 
    { 
        global $Filter, $user;

        $id = $Filter->clearInt($id);

        /* 
         * Fury;
         */
        if ($id == 1 && $user['class'] == 'warior') 
        {
            if ($user['skill_1_time'] < time() && $user['skill_1_active'] == 0) 
            {
                $param = round($user['strike'] * $user['skill_1_param'] / 100); // Percent of user['strike'];
                DB::$dbs->query("UPDATE " . USERS . " SET `strike` = ?, `skill_1_time` = ?, `skill_1_active` = ?, `skill_1_plus_param` = ? WHERE `id` = ?", [($user['strike'] + $param), (time() + 60), 1, $param, $user['id']]);
                $this->addLog($user['id'], '<span style="color: green;">Вы использовали Ярость +'. $param .'</span>');
            }
        } 
    }

    function skillPanel() 
    {
        global $user, $Filter;

        if (isset($_GET['useSkill']) && is_numeric($_GET['useSkill']) && $user['in_battle'] == 1) 
        {
            $skillId = $Filter->clearInt($_GET['useSkill']);
            $this->useSkill($skillId);
            header("Location: " . $this->deleteSkillId($_SERVER['REQUEST_URI'], $skillId));
        }

        $uri = ($_SERVER['SCRIPT_NAME'] == $_SERVER['REQUEST_URI'] ? $_SERVER['SCRIPT_NAME']. '?' : $_SERVER['REQUEST_URI']);

        echo '<div class="line"></div>';
        if ($user['class'] == 'warior') 
        {
            $timeReloadFury = $user['skill_1_time'] - time();
            
            
            if ($user['skill_1_time'] > time()) 
            {
                ?> 
                <a href="<?=$uri?>" class="link-touch"><img src="/img/user/skill/1/<?=$user['skill_1_lvl']?>.png" width="18px" height="18px"> Ярость <span class="count"><?=countTime($timeReloadFury)?></span></a>
                <?php
            } 
            else 
            {
                ?> 
                <a href="<?=$uri?>&amp;useSkill=1" class="link-touch"><img src="/img/user/skill/1/<?=$user['skill_1_lvl']?>.png" width="18px" height="18px"> Ярость</a>
                <?php
            }
        }
    } 
    
    function deleteBottleId ($str, $id) 
    {
        $filter = '&useBottle='.$id.'';
        $str = str_replace($filter, '', $str);
        return $str;
    }
    
    function useBottle($id) 
    {
        global $user, $Filter;
        
        $bottle = DB::$dbs->queryFetch("SELECT * FROM ". BELT ." WHERE `status` = ? and `user_id` = ? and `id` = ?", [1, $user['id'], $id]); 
        
        if (!empty($bottle) && $user['bottle_cooldown'] <= time()) 
        {
            if (empty($bottle['count'])) 
            {
                DB::$dbs->query("DELETE FROM ". BELT ." WHERE `id` = ? and `user_id` = ?", [$id, $user['id']]);
            } 
            else 
            {
                DB::$dbs->query("UPDATE ". BELT ." SET `count` = ? WHERE `id` = ? and `user_id` = ?", [($bottle['count'] - 1), $id, $user['id']]);
                
                if ($user['health'] + $bottle['restore'] > $user['max_health']) 
                {
                    $restore = $user['max_health'] - $user['health'];
                } 
                else 
                {
                    $restore = $bottle['restore'];
                } 
                
                DB::$dbs->query("UPDATE ". USERS ." SET `health` = ?, `bottle_cooldown` = ? WHERE `id` = ?", [($user['health'] + $restore), (time() + 25), $user['id']]);
                $this->addLog($user['id'], '<span style="color: green;">Вы использовали '. $Filter->clearString($bottle['name']) .' +'. $restore .'</span>');
            }
        }
    }
    
    function bottlePanel() 
    {
        global $user, $Filter;
        
        if (isset($_GET['useBottle']) && is_numeric($_GET['useBottle']) && $user['in_battle'] == 1) 
        {
            $bottleId = $Filter->clearInt($_GET['useBottle']);
            $this->useBottle($bottleId);
            header("Location: " . $this->deleteBottleId($_SERVER['REQUEST_URI'], $bottleId));
        } 
        
        $bottle = DB::$dbs->queryFetch("SELECT * FROM ". BELT ." WHERE `status` = ? and `user_id` = ?", [1, $user['id']]); 
        $uri = ($_SERVER['SCRIPT_NAME'] == $_SERVER['REQUEST_URI'] ? $_SERVER['SCRIPT_NAME']. '?' : $_SERVER['REQUEST_URI']);
        
        if (empty($bottle)) 
        {
            ?> 
            <div class="wrap">
                Отсутствует зелье.
            </div>
            <?php
        } 
        else 
        {
            ?> 
            <a href="<?=$uri . ($user['bottle_cooldown'] > time() ? null : '&amp;useBottle='. $bottle['id'])?>" class="link-touch"><img src="/ico/bottle/<?=$bottle['img']?>.png" width="18px" height="18px"> <?=$Filter->output($bottle['name'])?> x<?=$Filter->clearInt($bottle['count']) . ($user['bottle_cooldown'] > time() ? '<span class="count">'. countTime($user['bottle_cooldown'] - time()).'</span>' : null)?></a>
            <?php
        }
        
    }

    function addLog($userId, $text) 
    {
        if (!empty($userId) && !empty($text)) 
        {
            DB::$dbs->query("INSERT INTO ". LOG ." (`user_id`, `text`, `time`) VALUES (?, ?, ?)", [$userId, $text, time()]);
        } 
        else 
        {
            ?> 
                <div class="error">
                    Возникла ошибка при записи данных в логи 
                </div>
            <?php
        }
    }

    function readLog($userId) 
    {
        if (empty($userId)) 
        {
            ?> 
                <div class="error">
                    Возникла ошибка при записи данных в логи 
                </div>
            <?php
        } 
        else 
        {
            $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ". LOG ." WHERE `user_id` = ? ORDER BY `time` DESC", [$userId]);

            ?> 
                <div class="head">
                    Лог боя 
                </div>
            <?php
            if (empty($all)) 
            {
                ?> 
                    <div class="block">
                        Лог боя отсутствует
                    </div>
                <?php
            } 
            else 
            {
                $sql = DB::$dbs->query("SELECT `text`, `time` FROM ". LOG ." WHERE `user_id` = ? ORDER BY `time` DESC LIMIT 10", [$userId]);

                ?> 
                    <div class="block">
                <?php

                while ($log = $sql -> fetch()) 
                {
                    ?> 
                        <?=ico('attack.png') . $log['text']?> 
                        <span style="color: #404040;"> 
                            [<?=dataTime($log['time'])?>] 
                        </span><br/>
                    <?php
                } 
                ?> 
                    </div>
                <?php
            }
        }
    }

    function clearLog($userId) 
    {
        if (empty($userId)) 
        {
            ?> 
                <div class="error"> 
                    Не удалось очистить кэш боя! 
                </div>
            <?php
        } 
        else 
        {
            $ank = DB::$dbs->queryFetch("SELECT `id` FROM ". USERS ." WHERE `id` = ?", [$userId]);

            if (empty($ank)) 
            {
                ?> 
                    <div class="error"> 
                        Не удалось очистить кэш боя! 
                    </div>
                <?php
            } 
            else 
            {
                DB::$dbs->query("DELETE FROM ". LOG ." WHERE `user_id` = ?", [$userId]);
            }
        }
    }
    
    function addCooldown($userId) 
    {
        global $Filter;
    
        $userId = $Filter->clearInt($userId);
    
        DB::$dbs->query("UPDATE ". USERS ." SET `cooldown` = ? WHERE `id` = ?", [time(), $userId]);
    }

    function checkCooldown($userId, $time) 
    {
        global $Filter;
    
        $userId = $Filter->clearInt($userId);
        $ank    = DB::$dbs->queryFetch("SELECT `id`, `cooldown` FROM ". USERS ." WHERE `id` = ?", [$userId]);
    
        if ($ank['cooldown'] + $time > time()) 
        {
            $_SESSION['error'] = 'Ошибка! Не бей так часто.';
            //header("Location ". $_SERVER['REQUEST_URI'] ."?");
            return true;
        }
    }
}

