<?php

use Core\Db;
use User\Login;

const GAME = true;
include('_incl_data/__config.php');
include('_incl_data/class/__db_connect.php');
$u = User::start();

$logid = isset($_GET['log']) ? (int)$_GET['log'] : 0;

$btl = Battle::get($logid);
$based = 'battle_logs_save';

if (isset($btl['id'])) {
    $allprice = (int)Db::getValue('select sum(price1) from battle_users where battle = ? group by uid', [$btl['id']]);
    $allprice = Battle::getType($allprice, $btl['smert'] == 1);

    if ($btl['type'] == 99) {
        $allprice = '<span style="color: red;">' . str_replace(' ', '&nbsp;', $allprice[3]) . '</span>';
    } else {
        $allprice = str_replace(' ', '&nbsp;', $allprice[2]);
    }
}

function replaceLogText(array $d, string $text): string
{
    $d = [
        'login1' => $d['login1'] ?? '',
        'login2' => $d['login2'] ?? '',
        'prm' => $d['prm'] ?? '',
        'time1' => $d['time1'] ?? 0,
        'time2' => $d['time2'] ?? 0,
        't1' => $d['t1'] ?? 0,
        't2' => $d['t2'] ?? 0,
    ];

    $rep1 = <<<HTML
<span onclick="chat.addto('{$d['login1']}','to'); return false;" oncontextmenu="infoMenu('{$d['login1']}',event,'chat'); return false;" class="CSSteam{$d['t1']}">{$d['login1']}</span>
HTML;
    $rep2 = <<<HTML
<span onclick="chat.addto('{$d['login2']}','to'); return false;" oncontextmenu="infoMenu('{$d['login2']}',event,'chat'); return false;" class="CSSteam{$d['t2']}">{$d['login2']}</span>
HTML;

    $search = [
        '{u1}',
        '{u2}',
        '{pr}',
        '^^^^',
        '{tm1}',
        '{tm2}',
        '{tm3}',
        '{tm4}',
    ];

    $replace = [
        $rep1,
        $rep2,
        "<b>{$d['prm']}</b>",
        '=',
        '<span class="date">' . date('H:i', (int)$d['time1']) . '</span>',
        '<span class="date">' . date('H:i', (int)$d['time2']) . '</span>',
        '<span class="date">' . date('d.m.y H:i', (int)$d['time1']) . '</span>',
        '<span class="date">' . date('d.m.y H:i', (int)$d['time2']) . '</span>',
    ];

    return str_replace($search, $replace, $text);
}

function testlog($pl)
{
    global $log_text;
    if ($pl['type'] != 1 && $pl['type'] != 6) {
        return $pl['text'];
    }

    $d = [];

    foreach (explode('||', $pl['vars']) as $value) {
        $r = explode('=', $value);
        if (empty($r[0])) {
            continue;
        }
        $d[$r[0]] = $r[1];
    }

    # По неведомой причине команды в базу падают с id 0 и 1, а не 1 и 2. Что ломает все логи.
    if (isset($d['t1'], $d['t2'])) {
        $d['t1']++;
        $d['t2']++;
    }

    //обычный удар
    $rt = replaceLogText($d, $pl['text']);

    $k01 = 1;
    $zb1 = [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0];
    $zb2 = [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0];

    if (isset($d['bl1']) && $d['bl1'] > 0) {
        $b11 = 1;
        $b12 = $d['bl1'];
        while ($b11 <= $d['zb1']) {
            $zb1[$b12] = 1;
            if ($b12 >= 5 || $b12 < 0) {
                $b12 = 0;
            }
            $b12++;
            $b11++;
        }
    }

    if (isset($d['bl2']) && $d['bl2'] > 0) {
        $b11 = 1;
        $b12 = $d['bl2'];
        while ($b11 <= $d['zb2']) {
            $zb2[$b12] = 1;
            if ($b12 >= 5 || $b12 < 0) {
                $b12 = 0;
            }
            $b12++;
            $b11++;
        }
    }

    if (isset($d['t1'], $d['t2'])) {
        while ($k01 <= 5) {
            $zns01 = '';
            $zns02 = '';
            $j01 = 1;
            while ($j01 <= 5) {
                $zab1 = '0';
                $zab2 = '0';
                if ($j01 == $k01) {
                    $zab1 = '1';
                    $zab2 = '1';
                }

                $zab1 .= $zb1[$j01];
                $zab2 .= $zb2[$j01];

                $zns01 .= '<img src="//img.new-combats.tech/i/zones/' . $d['t1'] . '/' . $d['t2'] . $zab1 . '.gif">';
                $zns02 .= '<img src="//img.new-combats.tech/i/zones/' . $d['t2'] . '/' . $d['t1'] . $zab2 . '.gif">';

                $j01++;
            }
            $rt = str_replace('{zn1_' . $k01 . '}', $zns01, $rt);
            $rt = str_replace('{zn2_' . $k01 . '}', $zns02, $rt);
            $k01++;
        }
    }
    $j = 1;
    while ($j <= 21) {
        //замена R - игрок 1
        if (isset($d['s2'])) {
            $r = $log_text[$d['s1']][$j];
            $k = 0;
            if (is_array($r)) {
                while ($k <= count($r)) {
                    if (isset($log_text[$d['s1']][$j][$k])) {
                        $rt = str_replace('{1x' . $j . 'x' . $k . '}', $log_text[$d['s1']][$j][$k], $rt);
                    }
                    $k++;
                }
            }
        }

        //замена R - игрок 2
        if (isset($d['s2'])) {
            $r = $log_text[$d['s2']][$j];
            $k = 0;
            if (is_array($r)) {
                while ($k <= count($r)) {
                    if (isset($log_text[$d['s2']][$j][$k])) {
                        $rt = str_replace('{2x' . $j . 'x' . $k . '}', $log_text[$d['s2']][$j][$k], $rt);
                    }
                    $k++;
                }
            }
        }

        $j++;
    }
    //заменяем данные повторно
    $rt = replaceLogText($d, $rt);

    //закончили заменять
    $pl['text'] = $rt;

    return $pl['text'];
}

function getTeamColoredLogin(array $us): string
{
    $login = new Login($us['align'], $us['clan'], $us['level'], $us['login']);
    $us['team']++;
    return "<b class='CSSteam{$us['team']}'>$login->fullLogin</b>";
}

$r = '';
$p = '';

$b = <<<HTML
<table style="width: 100%; border: 0;" cellpadding="0" cellspacing="0">
    <tbody>
    <tr style="vertical-align: top;">
        <td style="vertical-align: bottom;">
            <input onClick="window.location.reload();" type="submit" name="analiz2" class="btn" value="Обновить">
HTML;

if ($btl['team_win'] != -1) {
    if (!isset($_GET['analiz'])) {
        $b .= <<<HTML
        <input onclick="location='/logs.php?log=$logid&analiz=1'" type="submit" name="analiz3" class="btn btn-success" value="Статистика">
        <span style="margin-left: 25px;">Поиск : <form id="line_filter" style="display: inline;" onsubmit="return false;">
            <input type="text" id="line_filter_input" autocomplete="off" style="padding:5px;">
            <input type="submit" id="line_filter_input_submit" class="btn" value="Фильтр" onclick="return false">
            <input type="button" id="line_filter_glow" class="btn" value="Подсветка"></form>
        </span>
        HTML;
    } else {
        $b .= <<<HTML
        <input onclick="location='/logs.php?log=$logid'" type="submit" name="analiz3" class="btn btn-danger" value="Лог боя">
        HTML;
    }
}

$b .= "</td></tr></tbody></table>";

if (isset($btl['id']) && $btl['team_win'] != -1 && isset($_GET['analiz'])) {
    function rzv($v): string
    {
        $v = explode('.', $v);
        return isset($v[1]) ? "$v[0].$v[1]" : "$v[0].0";
    }

    $tmStart = floor(($btl['time_over'] - $btl['time_start']) / 6) / 10;
    $tmStart = rzv($tmStart);
    $tbtl = '<img src="//img.new-combats.tech/i/fighttype' . $btl['type'] . '.gif" alt="">';
    if ($btl['invis'] > 0) {
        $tbtl .= '<img src="//img.new-combats.tech/i/fighttypehidden0.gif" alt="">';
    }

    $tbtl = "Тип боя: $tbtl (" . ($btl['type'] == 1 ? 'кулачный' : 'физический') . " поединок)  ";

    if ($btl['izlom'] > 0) {
        $tbtl .= 'Волна: ' . $btl['izlomRoundSee'] . ' &nbsp; &nbsp; ';
    }

    $tbtl .= 'Продолжительность боя: ' . $tmStart . ' мин.<br>';

    $users = [];
    $uids = [];

    //Поулчаем инфо
    $tpas = [
        1 => 'X',
        2 => '<span style="color: #AAAAEE; ">&bull;</span>',
        3 => '<b>&bull;</b>',
        4 => '<span style="color: #FF0000; ">&curren;</span>',
        5 => '<span style="color: #FF0000; ">X</span>',
        6 => '<span style="color: #AAAAEE; ">&bull;</span>',
        7 => '<span style="color:#777777; "><B>&bull;</B></span>',
        8 => '<span style="color: #AAAAEE; ">&bull;</span>',
    ];
    $tpbs = [
        0 => '',
        1 => '<B>&bull;</B>',
        2 => '<span style="color: #AAAAAA; "><B>&bull;</B></span>',
        3 => 'X',
        4 => '<span style="color: #FFEEEE; "><B>X</B></span>',
        5 => '<span style="color: #FFEEEE; "><B>&bull;</B></span>',
        6 => '<span style="color: #AAAAEE; "><B>&bull;</B></span>',
        7 => '<span style="color: #777777; "><B>&bull;</B></span>',
        8 => '<span style="color: #AAAAAA; "><B>&bull;</B></span>',
    ];

    $battleUsers = Db::getRows('select * from battle_users where battle = ?', [$btl['id']]);
    foreach ($battleUsers as $pl) {
        if (isset($uids[$pl['id']])) {
            continue;
        }
        $i = count($users);
        $users[$i] = $pl;
        $uids[$pl['uid']] = $i;

        $users[$i]['value'] = [
            'y' => 0, //уворотов+парирований+блоков щитом
            'b' => 0, //успешных блоков
            'p' => 0, //не успешных блоков, по персонажу попали
            'zb' => [ //Список зон блока

            ],
            'sa' => [ //Статистика ударов
                0 => '',
                1 => '',
                2 => '',
                3 => '',
                4 => '',
                5 => '',
            ],
            'sb' => [ //Статистика блоков
                0 => '',
                1 => '',
                2 => '',
                3 => '',
                4 => '',
                5 => '',
            ],
        ];

        $battleStatUser1 = Db::getRows('select * from battle_stat where battle = ? and uid1 = ? order by id', [$btl['id'], $pl['uid']]);
        foreach ($battleStatUser1 as $pl2) {
            if (!isset($users[$i]['yrn'])) {
                $users[$i]['yrn'] = 0;
            }
            if (!isset($users[$i]['yrn_krit'])) {
                $users[$i]['yrn_krit'] = 0;
            }
            if (!isset($users[$i]['ga'])) {
                $users[$i]['ga'] = 0;
            }
            if (!isset($users[$i]['gaa'])) {
                $users[$i]['gaa'] = 0;
            }
            if (!isset($users[$i]['gak'])) {
                $users[$i]['gak'] = 0;
            }
            if (!isset($users[$i]['zona'])) {
                $users[$i]['zona'] = [];
            }
            if (!isset($users[$i]['zonb'])) {
                $users[$i]['zonb'] = [];
            }

            //Обновляем данные
            $users[$i]['yrn'] += $pl2['yrn'];
            $users[$i]['yrn_krit'] += $pl2['yrn_krit'];
            //Статистика далее
            $users[$i]['gaa']++;
            if ($users[$i]['yrn'] > 0) {
                $users[$i]['ga']++;
            }
            if ($users[$i]['yrn_krit'] > 0) {
                $users[$i]['gak']++;
            }
            //Получаем куда бил игрок
            $j = 0;
            while ($j < $pl2['ma']) {
                if (!isset($pl2['a'][$j])) {
                    $j++;
                    continue;
                }

                if (!isset($users[$i]['zona'][$pl2['a'][$j]])) {
                    $users[$i]['zona'][$pl2['a'][$j]] = 0;
                }

                $users[$i]['zona'][$pl2['a'][$j]]++;
                $za = $pl2['a'][$j];
                $k = 1;
                while ($k <= 5) {
                    if ($za == $k) {
                        $tpa = $pl2['type_a'][$j];
                        $zag[$k] = true;
                        $users[$i]['value']['sa'][$k] .= $tpas[$tpa];
                    } else {
                        $zag[$k] = false;
                    }
                    $k++;
                }
                $j++;
            }
            $j = $pl2['b'];
            $k = 0;
            while ($k < $pl2['mb']) {
                if ($j > 5) {
                    $j = 1;
                }
                $users[$i]['value']['zb'][] = [0 => $j, 1 => 0];
                if (!isset($users[$i]['zonb'][$j])) {
                    $users[$i]['zonb'][$j] = 0;
                }
                $users[$i]['zonb'][$j]++;
                $j++;
                $k++;
            }
            //
            $k = 1;
            while ($k <= 5) {
                if (empty($zag[$k])) {
                    $users[$i]['value']['sa'][$k] .= ' ';
                }
                $k++;
            }
            //
        }
        //

        $battleStatUser2 = Db::getRows('select * from battle_stat where battle = ? and uid2 = ? order by id', [$btl['id'], $pl['uid']]);
        $k = 0;
        foreach ($battleStatUser2 as $pl2) {
            if (!isset($users[$i]['_yrn'])) {
                $users[$i]['_yrn'] = 0;
            }
            if (!isset($users[$i]['_yrn_krit'])) {
                $users[$i]['_yrn_krit'] = 0;
            }
            //Обновляем данные
            $users[$i]['_yrn'] -= $pl2['yrn'];
            $users[$i]['_yrn_krit'] -= $pl2['yrn_krit'];
            //Получаем куда били игрока
            $j = 0;
            $zag = [];
            while ($j < $pl2['ma']) {
                if (!isset($pl2['type_a'][$j])) {
                    $pl2['type_a'][$j] = 0;
                }
                $users[$i]['value']['zb'][$k][1] = $pl2['type_a'][$j];
                if ($pl2['type_a'][$j] == 2 || $pl2['type_a'][$j] == 6 || $pl2['type_a'][$j] == 7 || $pl2['type_a'][$j] == 8) {
                    $users[$i]['value']['y']++;
                } elseif ($pl2['type_a'][$j] == 3) {
                    $users[$i]['value']['b']++;
                } else {
                    $users[$i]['value']['p']++;
                }

                $j++;
            }

            $k++;

        }
        //Статистика блоков
        $k = 0;
        $h = 0;
        $bjj = [];

        while ($k < count($users[$i]['value']['zb'])) {
            $zb = (int)$users[$i]['value']['zb'][$k][0];
            $zt = (int)$users[$i]['value']['zb'][$k][1];
            $bjj[$zb] = true;
            $users[$i]['value']['sb'][$zb] .= $tpbs[$zt];
            if ($h < 1) {
                $h++;
            } else {
                $d = 1;
                while ($d <= 5) {
                    if (empty($bjj[$d])) {
                        $users[$i]['value']['sb'][$d] .= ' ';
                    }
                    $d++;
                }
                $bjj = [];
                $h = 0;
            }
            $k++;
        }
    }

    $usr = '';
    $tm = [];
    $tm_u = [];
    $tm_v = [];

    $i = 0;
    while ($i < count($users)) {
        if ($users[$i] > 0) {
            $us = $users[$i];
            if (!isset($tm[$us['team']])) {
                $tm[$us['team']] = '';
                $tm_v[] = (int)$us['team'];
            }
            $tm_u[$us['team']][] = $i;
            $tm[$us['team']] .= getTeamColoredLogin($us);
            $tm[$us['team']] .= ', ';
            unset($us);
        }
        $i++;
    }
    $i = 0;
    while ($i < count($tm_v)) {
        $usr .= rtrim($tm[$tm_v[$i]], ', ');
        if ($i < count($tm_v) - 1) {
            $usr .= ' &nbsp; <b>против</b> &nbsp; ';
        }
        $i++;
    }

    $strroll = '';
    foreach ($tm_v as $team) {
        $team_data = ['g' => false];
        foreach ($tm_u[$team] as $teamuser) {
            if ($users[$teamuser]['id'] < 1) {
                continue;
            }
            $rh = "{$users[$teamuser]['value']['sa'][1]}<br>{$users[$teamuser]['value']['sa'][2]}<br>
                    {$users[$teamuser]['value']['sa'][3]}<br>{$users[$teamuser]['value']['sa'][4]}<br>
                    {$users[$teamuser]['value']['sa'][5]}";
            $strroll .= '<tr>';
            $strroll .= "<td style='text-align: center' nowrap> " . getTeamColoredLogin($users[$teamuser]) . "</td>";
            $strroll .= "<td style='text-align: right' nowrap><pre>голову<br>грудь<br>живот<br>пояс<br>ноги</pre></td>";
            $strroll .= "<td style='font-size: 16px;' nowrap><pre>$rh</pre></td>";
            $strroll .= '</tr>';
        }
    }

    $usr = '<H4>Участники поединка</H4>' . $usr . '<br><br>';

    $r = <<<HTML
    <div>$b</div>
    <div>
        <span>$tbtl $p</span>
        <span style="float:right;">Статус битвы: <i>$allprice</i></span>
    </div>
    <br><br>$usr
    <div>$p</div>
    
    <h4>Последовательность ударов</h4>
    <table border=1 cellspacing=0 cellpadding=4>
    <tr><td style="text-align: center">Логин</td><td>Удар в</td><td>Последовательность ударов</td></tr>
    $strroll
    </table>
    
    (<b>X</b> - удачный удар,
    <b style="color: red;">¤</b> - критический удар пробив блок ,
    <b style="color: red;">X</b> - критический удар,
    <b style="color: red;"><code>Ξ</code></b> - крит + инвалидность,
    <b style="color: #006600;">X</b> - доп. магический удар,<BR>
    &nbsp;<b>•</b> - противник блокировал удар,
    <b style="color: #aaaaaa;">•</b> - увернулся,
    <b style="color: #aaaaee;">•</b> - парировал,
    <b style="color: #777777;">•</b> - отбил щитом)
    
    <H4>Последовательность блоков</H4>
    <table border=1 cellspacing=0 cellpadding=4>
    <tr><td style="text-align: center;">Логин</td><td>Блок</td><td>Последовательность блоков</td></tr>
    $strroll
    </table>

    (<b>X</b> - удачный блок,
    <b style="color: red;">X</b> - пробили блок критом,
    <b>•</b> - пропустил удар,
    <b style="color: #aaaaaa;">•</b> - увернулся,
    <b style="color: #aaaaee;">•</b> - парировал,
    <b style="color: #777777;">•</b> - отбил щитом)

    <h4>Суммарно</h4>
    <table border=1 cellspacing=0 cellpadding=4>
    <tr>
        <td style="text-align: center;"></td>
        <td style="text-align: center;">Логин</td>
        <td>Удары</td>
        <td>Блоки</td>
        <td>Попадания</td>
        <td>Защита</td>
        <td>Урон</td>
        <td>Потери</td>
        <td>Вылечено</td>
    </tr>
    HTML;

    foreach ($tm_v as $team) {
        $team_data = [
            'g' => false,
            'ga' => 0,
            'gaa' => 0,
            'gak' => 0,
            'hp' => 0,
            'hpAll' => 0,
            'yrn' => 0,
            'yrn_krit' => 0,
            '_yrn' => 0,
            '_yrn_krit' => 0,
            'val_b' => 0,
            'val_y' => 0,
            'val_p' => 0,
            'heal' => 0,
        ];

        foreach ($tm_u[$team] as $teamuser) {
            if ($users[$teamuser]['id'] < 1) {
                continue;
            }

            foreach ($team_data as $k => $v) {
                if ($k == 'g') {
                    continue;
                }
                if (!isset($users[$teamuser][$k])) {
                    $users[$teamuser][$k] = $v;
                }
            }

            $team_data['g'] = true;
            $users[$teamuser]['heal'] = $users[$teamuser]['hp'] - $users[$teamuser]['hpAll'] - $users[$teamuser]['_yrn'];
            $users[$teamuser]['heal'] = max($users[$teamuser]['heal'], 0);
            $users[$teamuser]['hp'] = max($users[$teamuser]['hp'], 0);
            $users[$teamuser]['yrn'] = max($users[$teamuser]['yrn'], 0);
            $users[$teamuser]['yrn_krit'] = max($users[$teamuser]['yrn_krit'], 0);
            $users[$teamuser]['_yrn'] = min($users[$teamuser]['_yrn'], 0);
            $users[$teamuser]['_yrn_krit'] = min($users[$teamuser]['_yrn_krit'], 0);
            $team_data['ga'] += $users[$teamuser]['ga'];
            $team_data['gaa'] += $users[$teamuser]['gaa'];
            $team_data['gak'] += $users[$teamuser]['gak'];
            $team_data['hp'] += $users[$teamuser]['hp'];
            $team_data['hpAll'] += $users[$teamuser]['hpAll'];
            $team_data['yrn'] += $users[$teamuser]['yrn'];
            $team_data['yrn_krit'] += $users[$teamuser]['yrn_krit'];
            $team_data['_yrn'] += $users[$teamuser]['_yrn'];
            $team_data['_yrn_krit'] += $users[$teamuser]['_yrn_krit'];
            $team_data['val_b'] += $users[$teamuser]['val_b'];
            $team_data['val_y'] += $users[$teamuser]['val_y'];
            $team_data['val_p'] += $users[$teamuser]['val_p'];
            $team_data['heal'] += $users[$teamuser]['heal'];
            $winw = '';
            if ($users[$teamuser]['hp'] === 0) {
                $users[$teamuser]['hp'] = '<span style="color: red;">0</span>';
                $winw = '<img title="Погиб" src="//img.new-combats.tech/i/ico/looses.gif" alt="Погиб">';
            } else {
                $winw = '<img title="Выжил" src="//img.new-combats.tech/i/ico/wins.gif" alt="Выжил">';
            }
            $coloredLogin = getTeamColoredLogin($users[$teamuser]);

            if (!isset($users[$teamuser]['zona'][1])) {
                $users[$teamuser]['zona'][1] = 0;
            }
            if (!isset($users[$teamuser]['zona'][2])) {
                $users[$teamuser]['zona'][2] = 0;
            }
            if (!isset($users[$teamuser]['zona'][3])) {
                $users[$teamuser]['zona'][3] = 0;
            }
            if (!isset($users[$teamuser]['zona'][4])) {
                $users[$teamuser]['zona'][4] = 0;
            }
            if (!isset($users[$teamuser]['zona'][5])) {
                $users[$teamuser]['zona'][5] = 0;
            }

            if (!isset($users[$teamuser]['zonb'][1])) {
                $users[$teamuser]['zonb'][1] = 0;
            }
            if (!isset($users[$teamuser]['zonb'][2])) {
                $users[$teamuser]['zonb'][2] = 0;
            }
            if (!isset($users[$teamuser]['zonb'][3])) {
                $users[$teamuser]['zonb'][3] = 0;
            }
            if (!isset($users[$teamuser]['zonb'][4])) {
                $users[$teamuser]['zonb'][4] = 0;
            }
            if (!isset($users[$teamuser]['zonb'][5])) {
                $users[$teamuser]['zonb'][5] = 0;
            }


            $r .= <<<HTML
            <tr>
                <td style="text-align: center; vertical-align: middle;">$winw</td>
                <td style="text-align: right;">$coloredLogin [{$users[$teamuser]['hp']}/{$users[$teamuser]['hpAll']}]</td>
                <td>{$users[$teamuser]['zona'][1]}/{$users[$teamuser]['zona'][2]}/{$users[$teamuser]['zona'][3]}/{$users[$teamuser]['zona'][4]}/{$users[$teamuser]['zona'][5]}</td>
                <td>{$users[$teamuser]['zonb'][1]}/{$users[$teamuser]['zonb'][2]}/{$users[$teamuser]['zonb'][3]}/{$users[$teamuser]['zonb'][4]}/{$users[$teamuser]['zonb'][5]}</td>
                <td style="text-align: center;">{$users[$teamuser]['ga']}(<span style="color: red;">{$users[$teamuser]['gak']}</span>)/{$users[$teamuser]['gaa']}</td>
                <td style="text-align: center;">{$users[$teamuser]['value']['b']}/{$users[$teamuser]['value']['y']}/{$users[$teamuser]['value']['p']}</td>
                <td style="text-align: center;">{$users[$teamuser]['yrn']}/<span style="color: red;">{$users[$teamuser]['yrn_krit']}</span></td>
                <td style="text-align: center;">{$users[$teamuser]['_yrn']}</td>
                <td style="text-align: center;">{$users[$teamuser]['heal']}</td>
            </tr>            
            HTML;
        }

        if (!$team_data['g']) {
            continue;
        }

        $winw = '--';
        if ($team_data['hp'] < 1) {
            $team_data['hp'] = 0;
        } else {
            $winw = '<img src="//img.new-combats.tech/i/flag.gif" title="Победитель" alt="Победитель">';
        }

        $r .= <<<HTML
        <tr style="background-color: #d2d0d0;">
            <td style="text-align: center;">$winw</td>
            <td style="text-align: right;"><b class="CSSteam$team">Всего [{$team_data['hp']}/{$team_data['hpAll']}]</b></td>
            <td> </td>
            <td> </td>
            <td style="text-align: center;">{$team_data['ga']}(<span style="color: red;">{$team_data['gak']}</span>)/{$team_data['gaa']}</td>
            <td style="text-align: center;">{$team_data['val_b']}/{$team_data['val_y']}/{$team_data['val_p']}</td>
            <td style="text-align: center;">{$team_data['yrn']}/<span style="color: red;">{$team_data['yrn_krit']}</span></td>
            <td style="text-align: center;">{$team_data['_yrn']}</td>
            <td style="text-align: center;">{$team_data['heal']}</td>
        </tr>
        HTML;
    }

    $r .= <<<HTML
    </table>
    Логин - имя персонажа и уровень жизни: [сейчас/всего]<br>
    Удары - статистика ударов по областям: голова/грудь/живот/пояс/ноги<br>
    Блоки - статистика блоков по областям: голова/грудь/живот/пояс/ноги<br>
    Попадания - удачных попаданий <span style="color: red;">(из них критов)</span> / всего ударов<br>
    Защита - ударов заблокировано / уворотов / пропущено ударов<br>
    Урон - выбито HP из противников / из них <span style="color: red;">критами</span><br>
    Потери - получено повреждений <br>
    Вылечено - восстановлено HP<br>
    HTML;

} elseif (!isset($btl['id'])) {
    $r = '<div style="text-align: center; margin-top: 16px;">Скорее всего Архивариус снова потерял пергамент с хрониками боев...</div>';
} else {
    include('jx/battle/log_text.php');

    $getp = $_GET['p'] ?? 0;
    $getp = (int)$getp;

    //Получаем логи
    $min = max((int)round(12 * ($getp - 1)), 0);
    $max = $min + 11;

    $based = 'battle_logs_save';

    $check = Db::getValue('select count(*) from battle_logs_save where battle = ? and id_hod between ? and ? order by id_hod, time', [$btl['id'], $min, $max]) < 1;

    if ($check) {
        $based = 'battle_logs';
    }

    //генерируем страницы
    $pmax = Db::getValue("select id_hod from $based where battle = ? order by id_hod desc limit 1", [$btl['id']]);

    $pmax = ceil($pmax / 12);

    if ($min > round(12 * ($pmax - 1))) {
        $min = round(12 * ($pmax - 1));
        $max = $min + 11;
    }

    $i = 1;
    $code = PassGen::intCode();
    while ($i <= $pmax) {
        if ($getp == $i || $getp > $pmax && $i == $pmax || $getp < 1 && $i == 1) {
            $p .= ' <a style="color:maroon" href="?log=' . $btl['id'] . '&p=' . $i . '&rnd=' . $code . '">' . $i . '</a> ';
        } else {
            $p .= ' <a href="?log=' . $btl['id'] . '&p=' . $i . '&rnd=' . $code . '">' . $i . '</a> ';
        }
        $i++;
    }

    $h = 0;
    $clr = '#f2e5e0';
    $cclr = '';

    $savedbattlelogs = Db::getRows("select * from $based where battle = ? and id_hod between ? and ? order by id_hod, id limit 200", [$btl['id'], $min, $max + 1]);
    foreach ($savedbattlelogs as $pl) {
        $pl['text'] = testlog($pl);
        $pl['text'] = str_replace('\"', '"', $pl['text']);
        if ($h != $pl['id_hod']) {
            if ($h > 0) {
                $clr = $clr == '#f2e5e0' ? '#f2e5e5' : '#f2e5e0';
                $cclr = 'border-top:1px solid #b1b1b1;';
            }
            $h = $pl['id_hod'];
        }
        $r .= '<div class="logs_php_line" style="background-color:' . $clr . ';' . $cclr . 'padding:1px;">' . $pl['text'] . '</div>';
        $cclr = '';
    }

    //собираем страницу
    $p = 'Страницы: ' . $p;
    $usr = '';

    if ($btl['team_win'] == -1) {
        $aliveusers = Db::getRows('select login, level, align, clan, team, hpNow, hpAll from users left join stats on users.id = stats.id where battle = ? and hpNow > 0', [$btl['id']]);
        $usrs = [-1 => []];

        foreach ($aliveusers as $pl) {
            if (!isset($usrs[$pl['team']])) {
                $usrs[$pl['team']] = '';
                $usrs[-1][count($usrs[-1])] = $pl['team'];
            }
            $hpnow = (int)ceil($pl['hpNow']);
            $hpall = (int)$pl['hpAll'];
            $usrs[$pl['team']] = getTeamColoredLogin($pl) . "[$hpnow/$hpall]";
        }

        if (count($usrs[-1]) > 0) {
            $i = 0;
            while ($i < count($usrs[-1])) {
                $usr .= rtrim($usrs[$usrs[-1][$i]], ',');
                if (count($usrs[-1]) > $i + 1) {
                    $usr .= ' &nbsp; <b>против</b> &nbsp; ';
                }
                $i++;
            }
        }

        if ($usr != '') {
            $usr = '<div style="text-align: center;">' . $usr . '</div><hr>';
        }
    }

    $tbtl = '<img src="//img.new-combats.tech/i/fighttype' . $btl['type'] . '.gif" />';
    if ($btl['invis'] > 0) {
        $tbtl .= '<img src="//img.new-combats.tech/i/fighttypehidden0.gif" alt="">';
    }
    if ($btl['type'] == 0) {
        $tbtl = 'Тип боя: ' . $tbtl . ' (физический поединок) &nbsp; &nbsp; ';
    } elseif ($btl['type'] == 1) {
        $tbtl = 'Тип боя: ' . $tbtl . ' (кулачный поединок) &nbsp; &nbsp; ';
    } elseif ($btl['type'] == 250) {
        $tbtl = '<img src="//img.new-combats.tech/i/fighttype50.gif" alt="">';
        $tbtl = 'Тип боя: ' . $tbtl . ' (Война Кланов) &nbsp; &nbsp; ';
    } elseif ($btl['smert'] == 1) {
        $tbtl = '<img src="//img.new-combats.tech/i/fighttype9.gif" alt="">';
        $tbtl = 'Тип боя: ' . $tbtl . ' (Жесточайшее Сражение) &nbsp; &nbsp; ';
    } else {
        $tbtl = 'Тип боя: ' . $tbtl . ' (физический поединок) &nbsp; &nbsp; ';
    }

    if ($btl['izlom'] > 0) {
        $tbtl .= 'Волна: ' . $btl['izlomRoundSee'] . ' &nbsp; &nbsp; ';
    }

    $r = <<<HTML
    <div>$b</div>
    <div>
        <span>$tbtl $p</span>
        <span style="float:right;">Статус битвы: <i>$allprice</i></span>
    </div>
    <br><hr>$r
    <div id="not_found" style="display: none; font-style: italic; text-align: center;">
        Ничего не найдено. Совсем не найдено...
    </div>
    <hr>$usr
    <div>$p</div>
    HTML;
}
?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <title>Архив: Поединки</title>
    <script src="js/jquery.js"></script>
    <script src="js/jqueryrotate.js"></script>
    <script src="js/jquery.zclip.js"></script>
    <script src="js/jquery.cookie.js"></script>
    <script src="js/title.js"></script>
    <script src="//img.new-combats.tech/js/gameEngine.js"></script>
    <script>
        hi_no_fm = 1;

        function maginfo(z, p, m, obj) {
            let r = '';
            r += '<b>' + $(obj).attr('magelogin') + '</b><br><br>';
            r += 'Мощь: ' + m + ', ';
            r += 'Защита: ' + z + ', ';
            r += 'Подавление: ' + p + '';
            return r;
        }
    </script>
    <link href="//img.new-combats.tech/css/main.css" rel="stylesheet">
    <style>
        body {
            background: url(/i/battle_log_04.jpg) right 0 repeat-x,
            url(/i/battle_log_16.jpg) left bottom repeat-x,
            url(/i/battle_log_08.jpg) left 0 repeat-y,
            url(/i/battle_log_11.jpg) right 0 repeat-y,
            #f2e5e0;
            min-height: 100vh;
            min-width: 400px;
        }

        h3 {
            text-align: center;
        }

        .ttl_css {
            position: absolute;
            padding: 2px 3px;
            background-color: #ffffcc;
            border: 1px solid #6F6B5E;
        }

        .CSSteam {
            font-weight: bold;
            cursor: pointer;
        }

        .CSSteam0 {
            font-weight: bold;
            cursor: pointer;
        }

        .CSSteam1 {
            font-weight: bold;
            color: #6666CC;
            cursor: pointer;
        }

        .CSSteam2 {
            font-weight: bold;
            color: #B06A00;
            cursor: pointer;
        }

        .CSSteam3 {
            font-weight: bold;
            color: #269088;
            cursor: pointer;
        }

        .CSSteam4 {
            font-weight: bold;
            color: #A0AF20;
            cursor: pointer;
        }

        .CSSteam5 {
            font-weight: bold;
            color: #0F79D3;
            cursor: pointer;
        }

        .CSSteam6 {
            font-weight: bold;
            color: #D85E23;
            cursor: pointer;
        }

        .CSSteam7 {
            font-weight: bold;
            color: #5C832F;
            cursor: pointer;
        }

        .CSSteam8 {
            font-weight: bold;
            color: #842B61;
            cursor: pointer;
        }

        .CSSteam9 {
            font-weight: bold;
            color: navy;
            cursor: pointer;
        }

        .CSSvs {
            font-weight: bold;
        }

        table {
            border: 1px solid black;
        }
    </style>
</head>

<body> <!--#E2E0E0 -->
<div style="max-width:95%; min-height: 100%; margin:0 auto;">
    <br><br>
    <div id="ttl" class="ttl_css" style="display:none;z-index:1111;"></div>
</div>
<div id="gi" class="gifin" style="display:none;z-index:1110;"></div>
<div style="margin: 0 20px 60px;">
    <h3>
        <IMG SRC="//img.new-combats.tech/i/fighttype2.gif" alt="">
        Бойцовский Клуб<?= $based != 'battle_logs' ? ' (Архив поединков)' : '' ?> &nbsp;
        <IMG SRC="//img.new-combats.tech/i/fighttype2.gif" alt="">
    </h3>
    <?= $r ?>
</div>
<br><br><br>

<script>
    $('#line_filter').submit(function () {
        $('#line_filter_input_submit').trigger('click');
    });

    $('#line_filter_glow').click(function () {
        const val = $('#line_filter_input').val();
        $(".logs_php_line").stop().css('background-color', '').show();
        $('#not_found').css('display', 'none');
        if (val) {
            $(".logs_php_line:contains('" + val + "')").css('background-color', '#f8f8ef'); //##f8f8ef ffff80
        }
    });

    $('#line_filter_input_submit').click(function () {
        $("#not_found").slideUp();
        const val = $('#line_filter_input').val();
        if (!val) {
            $(".logs_php_line").stop().css('background-color', '').show();
        } else {
            if ($.browser.msie || !1) {
                $(".logs_php_line").stop().css('background-color', '').hide();
                if (val) $(".logs_php_line:contains('" + val + "')").stop().show();
            } else {
                $(".logs_php_line").stop().css('background-color', '').slideUp();
                $(".logs_php_line:contains('" + val + "')").stop().slideDown();
            }
            setInterval('if ($(".logs_php_line:visible").length == 0) $("#not_found").slideDown();', 300);
        }
        return false;
    });

    $('#line_filter_input').keyup(function () {
        if ($('#line_filter_input').val() == '') {
            $('#line_filter_input_submit').trigger('click');
        }
    });

    jQuery.expr[":"].contains = function (elem, i, match, array) {
        return (elem.textContent || elem.innerText || jQuery.text(elem) || "").toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
    }
</script>
</body>
</html>