<?php
include_once ('core/base.php');
falseauth();
$header = 'Дуэль';
// Подключение func.php для get_arena_rank_data()
include_once ('core/func.php'); 
include_once ('core/head.php');

$action = fl($_GET['action']);
$_GET['skill'] = fl($_GET['skill']);
$_GET['potion'] = fl($_GET['potion']);

$battle = $base -> query('SELECT * FROM `pvp` WHERE `first_user` = "'.$u['id'].'" OR `second_user` = "'.$u['id'].'" LIMIT 1') -> fetch_assoc();

if(!$battle){
        if($u['battle'] == 'pvp') $base -> query('UPDATE `users` SET `battle` = "no" WHERE `id` = "'.$u['id'].'" LIMIT 1');
        header('Location: /location/');
        exit;
}else{

if($u['id'] == $battle['first_user']){
        $f_or_s = 'first';
        $f_or_s_enemy = 'second';
        $enemy = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$battle['second_user'].'" LIMIT 1') -> fetch_assoc();
}elseif($u['id'] == $battle['second_user']){
        $f_or_s = 'second';
        $f_or_s_enemy = 'first';
        $enemy = $base -> query('SELECT * FROM `users` WHERE `id` = "'.$battle['first_user'].'" LIMIT 1') -> fetch_assoc();
}

// --- ЛОГИКА АВТОАТАКИ БОТА ---
$enemy_attack_time_field = $f_or_s_enemy . '_user_time_attack';
$time_since_enemy_attack = time() - $battle[$enemy_attack_time_field];
$is_enemy_online = ($enemy['date_online'] > (time() - 600));

// Бот атакует, если противник офлайн ИЛИ прошло 3 секунды с последней атаки
if (!$is_enemy_online || $time_since_enemy_attack >= 3) {
   
   $enemy_weapon = $base->query('SELECT * FROM `users_items` WHERE `id` = "'.$enemy['equip_right'].'" LIMIT 1')->fetch_assoc();
   $enemy_type_attack = $enemy_weapon['attack_type'] == 'm_att' ? $enemy['m_att'] : $enemy['p_att'];
   
   // --- СТАБИЛИЗИРОВАННАЯ АТАКА ---
   $base_attack_value = $enemy_type_attack; 
   $enemy_damage = $base_attack_value + mt_rand(1, 5); // Базовый урон + небольшой рандом
   
   $enemy_critical = mt_rand(0, 100) < ($enemy['skill'] / 4);
   if ($enemy_critical) $enemy_damage *= 2;

   $my_defense_stat = $enemy_type_attack == $enemy['p_att'] ? $u['p_def'] : $u['m_def'];
   $my_def_reduction = mt_rand(intval($my_defense_stat / 2), $my_defense_stat);
   
   $final_damage = max(0, round($enemy_damage - $my_def_reduction));

   $my_dodge = mt_rand(0, 100) < ($u['agility'] / 4);
   
   if ($my_dodge) {
       $base->query('INSERT INTO `pvp_log` SET
           `pvp_id` = "'.$battle['id'].'",
           `text` = "'.$enemy['login'].' пытался атаковать, но '.$u['login'].' увернулся.",
           `user` = "'.$enemy['id'].'",
           `damage` = "0",
           `seen`= "0"');
       $_SESSION['enemy_fast_log'] = $enemy['login'].' промахнулся...';
   } elseif ($final_damage > 0) {
       // Наносим урон игроку, ограничивая HP нулем
       $new_hp = max(0, $u['hp'] - $final_damage); 
       $base->query('UPDATE `users` SET `hp` = "'.$new_hp.'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
       
       $log_critical = $enemy_critical ? ' Критический урон!' : '';
       $dmg_color = $enemy_critical ? 'red' : 'yellow';

       $base->query('INSERT INTO `pvp_log` SET
           `pvp_id` = "'.$battle['id'].'",
           `text` = "'.$enemy['login'].' нанёс '.$final_damage.' урона.'.$log_critical.'",
           `user` = "'.$enemy['id'].'",
           `damage` = "'.$final_damage.'",
           `critical` = "'.($enemy_critical ? 1 : 0).'",
           `attack_type` = "basic",
           `seen` = "0"');
       
       $_SESSION['enemy_fast_log'] = $enemy['login'].' нанёс <font color="'.$dmg_color.'"><b>'.$final_damage.'</b></font> урона.';
   } else {
       $base->query('INSERT INTO `pvp_log` SET
           `pvp_id` = "'.$battle['id'].'",
           `text` = "'.$enemy['login'].' промахнулся...",
           `user` = "'.$enemy['id'].'",
           `damage` = "0",
           `seen` = "0"');
       $_SESSION['enemy_fast_log'] = $enemy['login'].' нанёс <font color="yellow"><b>0</b></font> урона.';
   }
   
   // Обновляем время последней атаки противника (бота)
   $base->query('UPDATE `pvp` SET `'.$enemy_attack_time_field.'` = "'.time().'" WHERE `id` = "'.$battle['id'].'" LIMIT 1');
   
   // Перенаправляем для обновления интерфейса
   header('Location: /pvp/');
   exit;
}
// --- КОНЕЦ ЛОГИКИ АВТОАТАКИ БОТА ---


if($enemy['hp'] <= 0){
        // --- ПОБЕДА АКТИВНОГО ИГРОКА ($u) ---
        $hp = max(1, $u['hp']); 
   
   // 1. АКТИВНЫЙ ИГРОК ($u) - ПОБЕДИТЕЛЬ
   $new_points = $u['arena_points'] + 1;
   $new_rank_level = $u['arena_rank_level'];
   $current_rank_data = get_arena_rank_data($u['arena_rank_level']);

   $win_message_text = '<b>'.$enemy['login'].'</b> сражён! Вы получили Монету Арены.';

   if (!$current_rank_data['max_rank'] && $new_points >= $current_rank_data['required']) {
       $new_rank_level++;
       $new_points = $new_points - $current_rank_data['required'];
       $win_message_text = "Победа! Вы повысили ранг до ".get_arena_rank_data($new_rank_level)['rank_name']."!";
   }
   
   $base->query("UPDATE `users` SET
       `arena_points` = '{$new_points}',
       `arena_rank_level` = '{$new_rank_level}',
       `arena_rank_coins` = `arena_rank_coins` + 1,
       `arena_pvp_kills` = `arena_pvp_kills` + 1,
       `hp` = '".$hp."',
       `duel_wins` = `duel_wins` + '1',
       `battle` = 'no',
       `last_log` = '".$win_message_text."'
       WHERE `id` = '".$u['id']."' LIMIT 1");
   // ----------------------------

   // 2. ПАССИВНЫЙ ПРОТИВНИК ($enemy) - ПОРАЖЕНИЕ (БЕЗ ШТРАФА)
   // Пассивный игрок теряет HP/MP и поражение в дуэлях, но не ранг/очки.
   $base->query("UPDATE `users` SET
       `duel_loses` = `duel_loses` + '1',
       `hp` = '".intval($enemy['max_hp'] / 4)."',
       `mp` = '".intval($enemy['max_mp'] / 4)."',
       `battle` = 'no',
       `last_log` = 'Поражение. Ваш персонаж был атакован ботом.'
       WHERE `id` = '".$enemy['id']."' LIMIT 1");
   // ------------------------------------------

        if($uloc['pk'] == 1){
                $base -> query('UPDATE `users` SET
                        `world` = "'.$enemy['respawn_world'].'",
                        `x` = "'.$enemy['respawn_x'].'",
                        `y` = "'.$enemy['respawn_y'].'"
                        WHERE `id` = "'.$enemy['id'].'" LIMIT 1');
        }
        $base -> query('DELETE FROM `pvp_log` WHERE `pvp_id` = "'.$battle['id'].'"');
        $base -> query('DELETE FROM `pvp` WHERE `id` = "'.$battle['id'].'"');
        header('Location: /location/');
        exit;
        
//Поражение (Игрок $u проиграл)
        if($u['hp'] <= 0){
   
   // 1. АКТИВНЫЙ ИГРОК ($u) - ПОРАЖЕНИЕ (ЕСТЬ ШТРАФ)
   $loser_rank_level = $u['arena_rank_level'];
   $loser_points = $u['arena_points'] - 1;

   if ($loser_points < 0 && $loser_rank_level > 1) {
       $loser_rank_level--;
       $prev_rank_data = get_arena_rank_data($loser_rank_level);
       $loser_points = $prev_rank_data['required'] - 1; 
       $loss_message_text = "Поражение. Вы потеряли 1 очко и понизили свой ранг до ".get_arena_rank_data($loser_rank_level)['rank_name'].".";
   } else {
       $loser_points = max(0, $loser_points);
       $loss_message_text = 'Поражение. Вы потеряли 1 очко.';
   }
   
   $base->query("UPDATE `users` SET
       `arena_points` = '{$loser_points}',
       `arena_rank_level` = '{$loser_rank_level}',
       `duel_loses` = `duel_loses` + '1',
       `hp` = '".intval($u['max_hp'] / 4)."',
       `mp` = '".intval($u['max_mp'] / 4)."',
       `battle` = 'no',
       `last_log` = '".$loss_message_text."'
       WHERE `id` = '".$u['id']."' LIMIT 1");
   // ------------------------------------------
   
   // 2. ПАССИВНЫЙ ПРОТИВНИК ($enemy) - ПОБЕДИТЕЛЬ (ЕСТЬ НАГРАДА)
   // Пассивный игрок получает награду
   $winner_rank_level = $enemy['arena_rank_level'];
   $winner_points = $enemy['arena_points'] + 1;
   $current_rank_data = get_arena_rank_data($enemy['arena_rank_level']);

   $win_message_text = '<b>'.$u['login'].'</b> сражён! Вы получили Монету Арены.';

   if (!$current_rank_data['max_rank'] && $winner_points >= $current_rank_data['required']) {
       $winner_rank_level++;
       $winner_points = $winner_points - $current_rank_data['required'];
       $win_message_text = "Победа! Вы повысили ранг до ".get_arena_rank_data($winner_rank_level)['rank_name']."!";
   }

   $base->query("UPDATE `users` SET
       `arena_points` = '{$winner_points}',
       `arena_rank_level` = '{$winner_rank_level}',
       `arena_rank_coins` = `arena_rank_coins` + 1,
       `arena_pvp_kills` = `arena_pvp_kills` + 1,
       `duel_wins` = `duel_wins` + '1',
       `last_log` = '".$win_message_text."'
       WHERE `id` = '".$enemy['id']."' LIMIT 1");
   // ------------------------------------------
   
        if($uloc['pk'] == 1){
                $base -> query('UPDATE `users` SET
                        `world` = "'.$u['respawn_world'].'",
                        `x` = "'.$u['respawn_x'].'",
                        `y` = "'.$u['respawn_y'].'"
                        WHERE `id` = "'.$u['id'].'" LIMIT 1');
        }
        $base -> query('DELETE FROM `pvp_log` WHERE `pvp_id` = "'.$battle['id'].'"');
        $base -> query('DELETE FROM `pvp` WHERE `id` = "'.$battle['id'].'"');
        header('Location: /location/');
        exit;
        }
}

//Пьём зелья
if($action == 'potion'){
$potion = $base -> query('SELECT * FROM `users_items` WHERE `user` = "'.$u['id'].'" AND `what` = "potion" AND `id` = "'.$_GET['potion'].'" LIMIT 1') -> fetch_assoc();
        if($potion > 0){
                if($potion['id'] == $u['belt_slot_1'] OR $potion['id'] == $u['belt_slot_2'] OR $potion['id'] == $u['belt_slot_3']){
                $time_potion = (time() - $u['last_'.$potion['potion'].'_potion']);
                if($time_potion >= 30){
                        $new_hp = $u['hp'] + $potion['hp_regen'];
                        if($new_hp > $u['max_hp']) $new_hp = $u['max_hp'];
                        $new_mp = $u['mp'] + $potion['mp_regen'];
                        if($new_mp > $u['max_mp']) $new_mp = $u['max_mp'];
                        $base -> query('UPDATE `users` SET `hp` = "'.$new_hp.'", `mp` = "'.$new_mp.'", `last_'.$potion['potion'].'_potion` = "'.time().'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                        $new_amount = $potion['amount'] - 1;
                        if($new_amount <= 0){
                                if($potion['id'] == $u['belt_slot_1']) $slot = 1;
                                if($potion['id'] == $u['belt_slot_2']) $slot = 2;
                                if($potion['id'] == $u['belt_slot_3']) $slot = 3;
                                $base -> query('UPDATE `users` SET `belt_slot_'.$slot.'` = "0" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                                $base -> query('DELETE FROM `users_items` WHERE `id` = "'.$potion['id'].'"');
                        }
                        else $base -> query('UPDATE `users_items` SET `amount` = "'.$new_amount.'" WHERE `id` = "'.$potion['id'].'" LIMIT 1');
                        $base -> query('INSERT INTO `pvp_log` SET
                                `pvp_id` = "'.$battle['id'].'",
                                `text` = "'.$u['login'].' использовал '.$potion['name'].'."');
                        if($potion['potion'] == 'hp') $_SESSION['user_fast_log'] = 'Восстановлено <font color="lime"><b>'.$potion['hp_regen'].'</b></font> здоровья.';
                        if($potion['potion'] == 'mp') $_SESSION['user_fast_log'] = 'Восстановлено <font color="aqua"><b>'.$potion['mp_regen'].'</b></font> маны.';
                }
                }
        }
        header('Location: /pvp/');
        exit;
}

//Атака
if($action == 'attack'){
        
        
        $time_attack = (time() - $battle[''.$f_or_s.'_user_time_attack']);
        $weapon = $base -> query('SELECT * FROM `users_items` WHERE `id` = "'.$u['equip_right'].'" LIMIT 1') -> fetch_assoc();

        if(!$weapon){
                $type_attack = $u['p_att'];
        }else{
                if($weapon['attack_type'] == 'p_att') $type_attack = $u['p_att'];
                elseif($weapon['attack_type'] == 'm_att') $type_attack = $u['m_att'];
        }

        if($time_attack >= 3) $damage = $type_attack;
        if($time_attack == 2) $damage = $type_attack / 2;
        if($time_attack == 1) $damage = $type_attack / 4;
        if($time_attack <= 0){
                $damage = 0;
                $fast = true;
        }

        //Критический урон
        if(mt_rand(0,100) < ($u['skill'] / 4)){
                $damage = $damage * 2;
                $critical = true;
        }else{
                $damage = $damage;
                $critical = false;
        }

        // Защита противника
        $enemy_defense_stat = $type_attack == $u['p_att'] ? $enemy['p_def'] : $enemy['m_def'];
        $enemy_def = mt_rand(intval($enemy_defense_stat / 2), $enemy_defense_stat);
        if($enemy_def < 0) $enemy_def = 0;
        $damage = $damage - $enemy_def;
        $damage = round($damage);

        //Шанс уворота
        if(mt_rand(0,100) < ($enemy['agility'] / 4)) $dodge = true;
        else $dodge = false;

        if($dodge == true){
                $base -> query('INSERT INTO `pvp_log` SET
                                `pvp_id` = "'.$battle['id'].'",
                                `text` = "'.$u['login'].' пытался атаковать, но '.$enemy['login'].' увернулся.",
                                `user` = "'.$u['id'].'",
                                `damage` = "0",
                                `seen`= "0"');
                                
                $_SESSION['user_fast_log'] = 'Противник увернулся...';
                
        }        else        {

        if($damage > 0){
                if($critical == true) $log_critical = ' Критический урон!';
                if($critical == true) $crit = 1;
                else $crit = 0;
                // Наносим урон противнику, ограничивая HP нулем
       $new_hp = max(0, $enemy['hp'] - $damage);
                $base -> query('UPDATE `users` SET `hp` = "'.$new_hp.'" WHERE `id` = "'.$enemy['id'].'" LIMIT 1');
       
                $base -> query('INSERT INTO `pvp_log` SET
                        `pvp_id` = "'.$battle['id'].'",
                        `text` = "'.$u['login'].' нанёс '.$damage.' урона.'.$log_critical.'",
                        `user` = "'.$u['id'].'",
                        `damage` = "'.$damage.'",
                        `critical` = "'.$crit.'",
                        `attack_type` = "basic",
                        `seen` = "0"');
                if($critical == true) $_SESSION['user_fast_log'] = 'Вы нанесли <font color="red"><b>'.$damage.'</b></font> урона!';
                else $_SESSION['user_fast_log'] = 'Вы нанесли <font color="yellow"><b>'.$damage.'</b></font> урона.';
        }else{
                $base -> query('INSERT INTO `pvp_log` SET
                        `pvp_id` = "'.$battle['id'].'",
                        `text` = "'.$u['login'].' промахнулся...",
                        `user` = "'.$u['id'].'",
                        `damage` = "0",
                        `seen` = "0"');
                if($fast == true) $_SESSION['user_fast_log'] = 'Слишком часто...';
                else $_SESSION['user_fast_log'] = 'Вы нанесли <font color="yellow"><b>0</b></font> урона.';
        }
        }
        $base -> query('UPDATE `pvp` SET `'.$f_or_s.'_user_time_attack` = "'.time().'" WHERE `id` = "'.$battle['id'].'" LIMIT 1');
        header('Location: /pvp/');
        exit;
}

//Умение
if($action == 'skill'){
        $skill = $base -> query('SELECT * FROM `users_skills` WHERE `user` = "'.$u['id'].'" AND `id` = "'.$_GET['skill'].'" LIMIT 1') -> fetch_assoc();
        if(!$skill){
                        header('Location: /pvp/');
                        exit;
                }else{
                        if($u['mp'] < $skill['mp_need']){
                                header('Location: /pvp/');
                                exit;
                        }else{
                                $time_skill = (time() - $skill['cool_down_time']);
                                if($time_skill < $skill['cool_down']){
                                                header('Location: /pvp/');
                                                exit;
                                }else{
                                        if($skill['id'] == $u['skill_slot_1'] OR $skill['id'] == $u['skill_slot_2'] OR $skill['id'] == $u['skill_slot_3']){
                                        if($skill['type'] == 'attack'){
                                                
                                                $time_attack = (time() - $battle['user_time_attack']);

                                                if($skill['type_attack'] == 'p_att') $type_attack = $u['p_att'];
                                                elseif($skill['type_attack'] == 'm_att') $type_attack = $u['m_att'];

                                                if($time_attack >= 4) $damage = $type_attack;
                                                if($time_attack == 3) $damage = $type_attack / 3;
                                                if($time_attack == 2) $damage = $type_attack / 4;
                                                if($time_attack <= 1) $damage = 0;

                                                //Атакующее умение
                                                $damage = $damage + $skill['how_many'];

                                                //Критический урон
                                                if(mt_rand(0,100) < ($u['skill'] / 4)){
                                                        $damage = $damage * 2;
                                                        $critical = true;
                                                }else{
                                                        $damage = $damage;
                                                        $critiacal = false;
                                                }
                       
                       // Защита противника
                       $enemy_defense_stat = $type_attack == $u['p_att'] ? $enemy['p_def'] : $enemy['m_def'];
                       $enemy_def = mt_rand(intval($enemy_defense_stat / 2), $enemy_defense_stat);
                       if($enemy_def < 0) $enemy_def = 0;
                       $damage = $damage - $enemy_def;
                       $damage = round($damage);

                                                //Шанс уворота
                                                if(mt_rand(0,100) < ($enemy['agility'] / 4)) $dodge = true;
                                                else $dodge = false;

                                                if($dodge == true){
                                                        $base -> query('INSERT INTO `pvp_log` SET
                                                                        `pvp_id` = "'.$battle['id'].'",
                                                                        `text` = "'.$u['login'].' использовал '.$skill['name'].', но '.$enemy['login'].' увернулся.",
                                                                        `user` = "'.$u['id'].'",
                                                                        `damage` = "0",
                                                                        `seen` = "0"');
                                                        $_SESSION['user_fast_log'] = 'Вы промахнулись...';
                                                }else{
                                                if($damage > 0){
                                                        if($critical == true) $log_critical = ' Критический урон!';
                                                        $crit = $critical ? 1 : 0;
                                                        // Наносим урон противнику, ограничивая HP нулем
                           $new_hp = max(0, $enemy['hp'] - $damage);
                                                        $base -> query('UPDATE `users` SET `hp` = "'.$new_hp.'" WHERE `id` = "'.$enemy['id'].'" LIMIT 1');
                           
                                                        $base -> query('INSERT INTO `pvp_log` SET
                                                                `pvp_id` = "'.$battle['id'].'",
                                                                `text` = "'.$u['login'].' использовал '.$skill['name'].' и нанёс '.$damage.' урона.'.$log_critical.'",
                                                                `user` = "'.$u['id'].'",
                                                                `damage` = "'.$damage.'",
                                                                `critical` = "'.$crit.'",
                                                                `attack_type` = "skill",
                                                                `seen` = "0"');
                                                        if($critical == true) $_SESSION['user_fast_log'] = 'Вы нанесли <font color="magenta"><b>'.$damage.'</b></font> урона!';
                                                        else $_SESSION['user_fast_log'] = 'Вы нанесли <font color="violet"><b>'.$damage.'</b></font> урона.';
                                                }else{
                                                        $base -> query('INSERT INTO `pvp_log` SET
                                                                `pvp_id` = "'.$battle['id'].'",
                                                                `text` = "'.$u['login'].' использовал '.$skill['name'].', но промахнулся...",
                                                                `user` = "'.$u['id'].'",
                                                                `damage` = "0",
                                                                `seen` = "0"');
                                                        $_SESSION['user_fast_log'] = 'Вы промахнулись...';
                                                }

                                                }

                                                $base -> query('UPDATE `users` SET `mp` = `mp` - "'.$skill['mp_need'].'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                                                $base -> query('UPDATE `users_skills` SET `cool_down_time` = "'.time().'" WHERE `id` = "'.$skill['id'].'" LIMIT 1');
                                                header('Location: /pvp/');
                                                exit;

                                        }elseif($skill['type'] == 'heal'){
                                                //Лечащее умение
                                                $new_hp = $u['hp'] + $skill['how_many'];
                                                if($new_hp > $u['max_hp']) $new_hp = $u['max_hp'];

                                                $base -> query('UPDATE `users` SET `hp` = "'.$new_hp.'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                                                $base -> query('INSERT INTO `pvp_log` SET
                                                        `pvp_id` = "'.$battle['id'].'",
                                                        `text` = "'.$u['login'].' использовал на себя '.$skill['name'].' и восстановил '.$skill['how_many'].' единиц здоровья."');
                                                $_SESSION['user_fast_log'] = 'Восстановлено <font color="lime"><b>'.$skill['how_many'].'</b></font> здоровья.';
                                                $base -> query('UPDATE `users` SET `mp` = `mp` - "'.$skill['mp_need'].'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                                                $base -> query('UPDATE `users_skills` SET `cool_down_time` = "'.time().'" WHERE `id` = "'.$skill['id'].'" LIMIT 1');
                                                header('Location: /pvp/');
                                                exit;

                                        }elseif($skill['type'] == 'massive_heal'){
                                                //...
                                        }elseif($skill['type'] == 'buff'){
                                                //...
                                        }
                                                
                                                $base -> query('UPDATE `users` SET `mp` = `mp` - "'.$skill['mp_need'].'" WHERE `id` = "'.$u['id'].'" LIMIT 1');
                                                $base -> query('UPDATE `users_skills` SET `cool_down_time` = "'.time().'" WHERE `id` = "'.$skill['id'].'" LIMIT 1');
                                                header('Location: /pvp/');
                                                exit;
                                        }
                                }
                        }
                }
        }
}

// --- ОПРЕДЕЛЕНИЕ ФОНА (FIXED) ---
$background = '/images/places/arena_bg.png'; // Фиксированный фон Арены
// ---------------------------------

echo '<div class="border" style="margin-top: 5px; box-sizing: border-box;">';
echo '<div style="width: 100%; max-width: 336px; height: 248px; background: url('.$background.') no-repeat center; background-size: cover;">';

//Быстрые логи
echo '<table width="100%" height="15%" style="font-size: 10px; text-shadow: black 1px 1px 1px; color: white;"><tr>';
echo '<td width="50%" valign="top">';
if(isset($_SESSION['user_fast_log'])){
        echo '<div class="fast_log">';
        echo '<center>'.$_SESSION['user_fast_log'].'</center>';
        echo '</div>';
        unset($_SESSION['user_fast_log']);
}
echo '</td>';
echo '<td width="50%" valign="top">';
$enemy_log = $base -> query('SELECT * FROM `pvp_log` WHERE `pvp_id` = "'.$battle['id'].'" AND `user` = "'.$enemy['id'].'" AND `seen` = "0" ORDER BY `id` DESC LIMIT 1');
$enemy_log_nr = $enemy_log -> num_rows;
if($enemy_log_nr > 0){
        $enemy_log = $enemy_log -> fetch_assoc();
        echo '<div class="fast_log">';
        if($enemy_log['damage'] > 0){
                if($enemy_log['attack_type'] == 'basic'){
                        if($enemy_log['critical'] == 1) $dmg_color = 'red';
                        else $dmg_color = 'yellow';
                }elseif($enemy_log['attack_type'] == 'skill'){
                        if($enemy_log['critical'] == 1) $dmg_color = 'magenta';
                        else $dmg_color = 'violet';
                }
                echo '<center>'.$enemy['login'].' нанёс <font color="'.$dmg_color.'">'.$enemy_log['damage'].'</font> урона.</center>';
        }elseif($enemy_log['damage'] == 0){
                echo '<center>'.$enemy['login'].' промахнулся...</center>';
        }
        echo '</div>';
        $base -> query('UPDATE `pvp_log` SET `seen` = "1" WHERE `pvp_id` = "'.$battle['id'].'" AND `seen` = "0" LIMIT 1');
}
echo '</td></tr></table>';

$enemy_skin = '/images/skins/'.$enemy['skin'].'_left.gif';
$enemy_hp_percents = round(max(0, $enemy['hp'])/$enemy['max_hp']*100,1);
if($enemy_hp_percents > 100) $enemy_hp_percents = 100;

echo '<table width="100%" height="85%" style="position: relative;"><tr><td width="50%"><center>';
echo '<tr><td width="50%"><center>';
        $buffs_q = $base -> query('SELECT * FROM `buffs` WHERE `user` = "'.$u['id'].'"');
        $buffs_nr = $buffs_q -> num_rows;
        echo '<div style="position: absolute; bottom: 35%; left: 10%; width: 35%;"><font style="text-shadow: black 1px 1px 1px; color: '.$u['login_color'].'; font-size: 12px;">'.$u['login'].'</font><br/>
        <div class="hp_small" style="background-size: '.$now_hp.'% 2px;"></div><br/>
        <div class="mp_small" style="background-size: '.$now_mp.'% 2px;"></div><br/><img src="/images/skins/'.$u['skin'].'_right.gif"></div>';
        if($buffs_nr > 0){
                        echo '<div style="position: absolute; bottom: 51%; left: 10%; width: 25%; padding-left: 5%;" align="left">';
                        while($buffs = $buffs_q -> fetch_assoc()){
                                $buff = $base -> query('SELECT * FROM `skills` WHERE `id` = "'.$buffs['buff'].'" LIMIT 1') -> fetch_assoc();
                                $buff_remain_time = ($buffs['time'] + $buff['duration']) - time();
                                $remain_percents = round($buff_remain_time / $buff['duration'] * 100,1);
                                echo '<div style="background: black; width: 10px; border: 1px solid black; display: inline-block;"><img src="/images/skills/'.$buff['image'].'.png" style="width: 10px;"><br/><div style ="background: #28BD28; height: 1px; width: '.$remain_percents.'%; display: inline-block;"></div></div>';
                        }
                        echo '</div>';
        }
echo '<td width="50%" style="padding-top: 20px;"><a href="/pvp/attack/"><center><small><font style="text-shadow: black 1px 1px 1px; color: '.$enemy['login_color'].';">'.$enemy['login'].'</font></small><br/><img src="'.$enemy_skin.'"><br/>
<div class="hp" style="width: 75%; background-size: '.$enemy_hp_percents.'% 12px; text-shadow: black 0 1px 0;  text-align: left;"><font color="#E0E0E0" size="1">HP: '.n_f(max(0, $enemy['hp'])).'/'.n_f($enemy['max_hp']).'</font></div></center></a>';

//Кнопка атаки
echo '<br/><br/><div style="position: absolute; bottom: 0.5%; right: 0.5%;">';
if($u['equip_right'] == '0'){
        echo '<a href="/pvp/attack/"><img  src="/images/skills/punch.png" style=" border: 1px solid #B1B1B1;" width="40px"></a>';
}else{
        $weapon = $base -> query('SELECT * FROM `users_items` WHERE `id` = "'.$u['equip_right'].'" LIMIT 1') -> fetch_assoc();
        if($weapon['mark'] == '0') $border_color = 'B1B1B1';
        if($weapon['mark'] == '1') $border_color = '30C030';
        if($weapon['mark'] == '2') $border_color = '68A8F9';
        if($weapon['mark'] == '3') $border_color = 'D8CD32';
        if($weapon['mark'] == '4') $border_color = 'DD4FFF';
        
        if (file_exists($_SERVER['DOCUMENT_ROOT'].'/images/items/right/'.$weapon['image'].'.png'))
        echo '<a href="/pvp/attack/"><img src="/images/items/right/'.$weapon['image'].'.png" style=" border: 1px solid #'.$border_color.';" width="40px"></a>';
        else
        echo '<a href="/pvp/attack/"><img src="/images/items/right/'.$weapon['image'].'" style=" border: 1px solid #'.$border_color.';" width="40px"></a>';

}

echo '</td></tr></table></div></div>';

//Действия
echo '<center>';
echo '<table style="width: 100%; max-width: 303px;" cellspacing="3px" style=""></tr>';
echo '<td class="event" width="50%">';
//Пояс с зельями
if($u['belt_slot_1'] > 0){
                $bs = $base -> query("SELECT * FROM `users_items` WHERE `id` = '".$u['belt_slot_1']."' LIMIT 1") -> fetch_assoc();
                $time_potion = (time() - $u['last_'.$bs['potion'].'_potion']);
                $time_cool_down_potion = 30 - (time() - $u['last_'.$bs['potion'].'_potion']);
                if($bs['mark'] == '0') $border_color = 'B1B1B1';
                if($bs['mark'] == '1') $border_color = '30C030';
                if($bs['mark'] == '2') $border_color = '68A8F9';
                if($bs['mark'] == '3') $border_color = 'D8CD32';
                if($bs['mark'] == '4') $border_color = 'DD4FFF';
                if($time_potion >= 30){
                        echo '<a class="potion" style="width: 42px; height: 42px; border: 1px solid #'.$border_color.';" href="/pvp/potion/'.$bs['id'].'/"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42; height: 42px;">
                        <div style="padding-top: 70%; padding-right: 3px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px; float: right;">'.$bs['amount'].'</font></div></div></a>';
                }else{
                        echo '<div class="potion" style="width: 42px; height: 42px; border: 1px solid gray;"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42px; height: 42px;">
                        <div style="background: url(/images/skills/opacity.png) no-repeat center; background-size: 100%; width: 42px; height: 42px;">
                        <div style="padding-top: 14px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px;">'.tl($time_cool_down_potion).'</font></div></div></div></div>';
                }
        }else{
                echo '<div class="potion" style="border: 1px solid gray; height: 31px; width: 42px;font-size: 13px; padding-top: 11px; display: inline-block; color: gray;">пусто</div>';
        }
if($u['belt_slot_2'] > 0){
                $bs = $base -> query("SELECT * FROM `users_items` WHERE `id` = '".$u['belt_slot_2']."' LIMIT 1") -> fetch_assoc();
                $time_potion = (time() - $u['last_'.$bs['potion'].'_potion']);
                $time_cool_down_potion = 30 - (time() - $u['last_'.$bs['potion'].'_potion']);
                if($bs['mark'] == '0') $border_color = 'B1B1B1';
                if($bs['mark'] == '1') $border_color = '30C030';
                if($bs['mark'] == '2') $border_color = '68A8F9';
                if($bs['mark'] == '3') $border_color = 'D8CD32';
                if($bs['mark'] == '4') $border_color = 'DD4FFF';
                if($time_potion >= 30){
                        echo '<a class="potion" style="width: 42px; height: 42px; border: 1px solid #'.$border_color.';" href="/pvp/potion/'.$bs['id'].'/"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42; height: 42px;">
                        <div style="padding-top: 70%; padding-right: 3px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px;">'.tl($time_cool_down_potion).'</font></div></div></a>';
                }else{
                        echo '<div class="potion" style="width: 42px; height: 42px; border: 1px solid gray;"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42px; height: 42px;">
                        <div style="background: url(/images/skills/opacity.png) no-repeat center; background-size: 100%; width: 42px; height: 42px;">
                        <div style="padding-top: 14px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px;">'.tl($time_cool_down_potion).'</font></div></div></div></div>';
                }
        }else{
                echo '<div class="potion" style="border: 1px solid gray; height: 31px; width: 42px;font-size: 13px; padding-top: 11px; display: inline-block; color: gray;">пусто</div>';
        }
if($u['belt_slot_3'] > 0){
                $bs = $base -> query("SELECT * FROM `users_items` WHERE `id` = '".$u['belt_slot_3']."' LIMIT 1") -> fetch_assoc();
                $time_potion = (time() - $u['last_'.$bs['potion'].'_potion']);
                $time_cool_down_potion = 30 - (time() - $u['last_'.$bs['potion'].'_potion']);
                if($bs['mark'] == '0') $border_color = 'B1B1B1';
                if($bs['mark'] == '1') $border_color = '30C030';
                if($bs['mark'] == '2') $border_color = '68A8F9';
                if($bs['mark'] == '3') $border_color = 'D8CD32';
                if($bs['mark'] == '4') $border_color = 'DD4FFF';
                if($time_potion >= 30){
                        echo '<a class="potion" style="width: 42px; height: 42px; border: 1px solid #'.$border_color.';" href="/pvp/potion/'.$bs['id'].'/"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42; height: 42px;">
                        <div style="padding-top: 70%; padding-right: 3px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px;">'.tl($time_cool_down_potion).'</font></div></div></a>';
                }else{
                        echo '<div class="potion" style="width: 42px; height: 42px; border: 1px solid gray;"><div style="background: url(/images/items/resource/'.$bs['image'].'.png) no-repeat center; background-size: 100%; display: inline-block; width: 42px; height: 42px;">
                        <div style="background: url(/images/skills/opacity.png) no-repeat center; background-size: 100%; width: 42px; height: 42px;">
                        <div style="padding-top: 14px;"><font style="text-shadow: black 1px 1px 1px; color: #e0e0e0; font-size: 10px;">'.tl($time_cool_down_potion).'</font></div></div></div></div>';
                }
        }else{
                echo '<div class="potion" style="border: 1px solid gray; height: 31px; width: 42px;font-size: 13px; padding-top: 11px; display: inline-block; color: gray;">пусто</div>';
        }
echo '</td>';
echo '</tr></table>';
echo '</center>';

//Лог
$log_q = $base -> query('SELECT * FROM `pvp_log` WHERE `pvp_id` = "'.$battle['id'].'" ORDER BY `id` DESC LIMIT 3');
$log_nr = $log_q -> num_rows;

if($log_nr > 0){

echo '<center><table style="width: 100%; max-width: 335px;"><tr><td class="event">';
while($log = $log_q -> fetch_assoc()){
        echo '<div style="margin-top: 2px; color: #B1B1B1; font-size: 12px;"><img src="/images/icons/topic.png" width="16px"> '.$log['text'].'</div>';
}
echo '</td></tr></table></center>';

}

}

include_once ('core/foot.php');
?>