<script>
    let elem = document.getElementById('se-pre-con');
    elem.parentNode.removeChild(elem);
</script>

<?php

use Insallah\Db;

if (!defined('GAME')) {
    die();
}

const TIERS = 'Ранги';
const PRIZE = 'Награда';

$achievement_data = [
    'zb' => [
        'quest' => 'Выполнить задания бабки.',
        'check' => ['Заданий', 5, 25, 50, 100, 250],
        'prize' => ['Жетон <br>успеха <br>', 5, 20, 40, 60, 100],
        'startlink' => 11
    ],
    'vx' => [
        'quest' => 'Победить в хаотических боях.',
        'check' => ['Побед', 50, 300, 400, 500, 1000],
        'prize' => ['екр.', 25, 50, 75, 100, 200],
        'startlink' => 21
    ],
    'snt' => [
        'quest' => 'Открыть сундук трупожора.',
        'check' => ['Открытий', 5, 25, 50, 100, 250],
        'prize' => ['екр.', 10, 25, 50, 75, 200],
        'startlink' => 31
    ],
    'rp' => [
        'quest' => 'Получить руну при плавке плохих заготовок. [S]',
        'check' => ['Рун', 5, 10, 25, 50, 100],
        'prize' => ['Плохие <br> заготовки <br>', 5, 7, 10, 12, 15],
        'startlink' => 41
    ],
    'rn' => [
        'quest' => 'Получить руну при плавке нормальных заготовок. [M]',
        'check' => ['Рун', 5, 10, 15, 25, 50],
        'prize' => ['Нормальные <br> заготовки <br>', 5, 7, 9, 12, 15],
        'startlink' => 51
    ],
    'rb' => [
        'quest' => 'Получить руну при плавке идеальных заготовок. [L]',
        'check' => ['Рун', 2, 5, 8, 11, 15],
        'prize' => ['Идеальные <br> заготовки <br>', 2, 4, 6, 10, 15],
        'startlink' => 61
    ],
    'pg' => [
        'quest' => 'Поучаствовать в героическом сражении.',
        'check' => ['Участий', 100, 200, 400, 600, 1000],
        'prize' => ['Жетон <br>успеха <br>', 10, 20, 40, 60, 80],
        'startlink' => 71
    ],
    'bv' => [
        'quest' => 'Продать бабушке найденные вещи в пещере.',
        'check' => ['Продаж', 5, 25, 50, 100, 250],
        'prize' => ['кр.', 500, 1000, 2000, 4000, 5000],
        'startlink' => 81
    ],
    'kw' => [
        'quest' => 'Победить в клановой войне.',
        'check' => ['Побед', 5, 10, 15, 20, 25],
        'prize' => ['Свиток <br> кланового<br> опыта ', 1, 2, 5, 10, 15],
        'startlink' => 91
    ],
    'pa' => [ # not implemented!
        'quest' => 'Получить покровительство Ангела.',
        'check' => ['Получено', 5, 25, 50, 100, 250],
        'prize' => null,
        'startlink' => null
    ],
    'bs' => [
        'quest' => 'Победы в башне смерти.',
        'check' => ['Побед', 1, 5, 10, 50, 500],
        'prize' => ['екр.', 1, 5, 10, 50, 200],
        'startlink' => 101
    ],
    'trn' => [ # not implemented!
        'quest' => 'Победы в турнирах.',
        'check' => ['Побед', 25, 50, 100, 200, 500],
        'prize' => ['екр.', 25, 25, 25, 25, 50],
        'startlink' => 111
    ],
];

function table($rows, $class = '', $fill = false)
{
    $c = '';
    $max_rows = sizeof(max($rows));

    foreach ($rows as $row) {
        if ($fill && sizeof($row) < $max_rows) {
            $row = array_merge($row, array_fill(0, $max_rows - sizeof($row), ''));
        }

        $c .= '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
    }

    return (!empty($class) ? "<table class='$class'>" : '<table>') . $c . '</table>' . PHP_EOL;
}

$ai = $u->achivInf($u->info['id'], 1);
if (isset($_GET['nagr'])) {
    $nagrtxt = 'За выполненное достижение Вы получили ';
    if (
        in_array($_GET['nagr'], [14, 15, 24, 25, 34, 35, 44, 45, 54, 55, 64, 65, 74, 75, 84, 85, 94, 95, 104, 105]) &&
        $u->info['level'] < 9
    ) {
        $nagrtxt = 'Вы не можете получить эту награду на этом уровне!';
    } elseif ( //бабка задание zb
        in_array($_GET['nagr'], [11, 12, 13, 14, 15]) &&
        in_array($ai['zb_n'], [0, 1, 2, 3, 4]) &&
        $ai['klaszb'] > $ai['zb_n']
    ) {
        $ai['zb_n'] += 1;
        $u->rangup($u->info['id'], $ai['zb_n'], 'zb');
        $i = 0;
        while ($i < $achievement_data['zb']['prize'][$ai['zb_n']]) {
            $u->addItem(10020, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Жетон успеха X' . $achievement_data['zb']['prize'][$ai['zb_n']];
    } elseif ( //Хаот задание vx
        in_array($_GET['nagr'], [21, 22, 23, 24, 25]) &&
        in_array($ai['vx_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasvx'] > $ai['vx_n']
    ) {
        $ai['vx_n'] += 1;
        $u->rangup($u->info['id'], $ai['vx_n'], 'vx');
        Db::sql('update users set money2 = money2 + ? where id = ?',
            [$achievement_data['vx']['prize'][$ai['vx_n']], $u->info['id']]);
        $nagrtxt .= $achievement_data['vx']['prize'][$ai['vx_n']] . $achievement_data['vx']['prize'][0];
    } elseif ( //Сундуки трупожора snt
        in_array($_GET['nagr'], [31, 32, 33, 34, 35]) &&
        in_array($ai['snt_n'], [0, 1, 2, 3, 4]) &&
        $ai['klassnt'] > $ai['snt_n']
    ) {
        $ai['snt_n'] += 1;
        $u->rangup($u->info['id'], $ai['snt_n'], 'snt');
        Db::sql('update users set money2 = money2 + ? where id = ?',
            [$achievement_data['snt']['prize'][$ai['snt_n']], $u->info['id']]);
        $nagrtxt .= $achievement_data['snt']['prize'][$ai['snt_n']] . $achievement_data['snt']['prize'][0];
    } elseif ( //Руны 8 лвл. rp
        in_array($_GET['nagr'], [41, 42, 43, 44, 45]) &&
        in_array($ai['rp_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasrp'] > $ai['rp_n']
    ) {
        $ai['rp_n'] += 1;
        $u->rangup($u->info['id'], $ai['rp_n'], 'rp');
        $i = 0;
        while ($i < $achievement_data['rp']['prize'][$ai['rp_n']]) {
            $u->addItem(10038, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Плохие Заготовки X' . $achievement_data['rp']['prize'][$ai['rp_n']];
    } elseif ( //Руны 9 лвл. rn
        in_array($_GET['nagr'], [51, 52, 53, 54, 55]) &&
        in_array($ai['rn_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasrn'] > $ai['rn_n']
    ) {
        $ai['rn_n'] += 1;
        $u->rangup($u->info['id'], $ai['rn_n'], 'rn');
        $i = 0;
        while ($i < $achievement_data['rn']['prize'][$ai['rn_n']]) {
            $u->addItem(10039, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Нормальные Заготовки X' . $achievement_data['rn']['prize'][$ai['rn_n']];
    } elseif ( //Руны 10 лвл. rb
        in_array($_GET['nagr'], [61, 62, 63, 64, 65]) &&
        in_array($ai['rb_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasrb'] > $ai['rb_n']
    ) {
        $ai['rb_n'] += 1;
        $u->rangup($u->info['id'], $ai['rb_n'], 'rb');
        $i = 0;
        while ($i < $achievement_data['rb']['prize'][$ai['rb_n']]) {
            $u->addItem(10040, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Идеальные Заготовки X' . $achievement_data['rb']['prize'][$ai['rb_n']];
    } elseif ( //Героик pg
        in_array($_GET['nagr'], [71, 72, 73, 74, 75]) &&
        in_array($ai['pg_n'], [0, 1, 2, 3, 4]) &&
        $ai['klaspg'] > $ai['pg_n']
    ) {
        $ai['pg_n'] += 1;
        $u->rangup($u->info['id'], $ai['pg_n'], 'pg');
        $i = 0;
        while ($i < $achievement_data['pg']['prize'][$ai['pg_n']]) {
            $u->addItem(10020, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Жетон Успеха X' . $achievement_data['pg']['prize'][$ai['pg_n']];
    } elseif ( //Продать бабушке найденные вещи в пещере bv
        in_array($_GET['nagr'], [81, 82, 83, 84, 85]) &&
        in_array($ai['bv_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasbv'] > $ai['bv_n']
    ) {
        $ai['bv_n'] += 1;
        $u->rangup($u->info['id'], $ai['bv_n'], 'bv');
        Db::sql('update users set money = money + ? where id = ?',
            [$achievement_data['bv']['prize'][$ai['bv_n']], $u->info['id']]);
        $nagrtxt .= $achievement_data['bv']['prize'][$ai['bv_n']] . $achievement_data['bv']['prize'][0];
    } elseif ( //Клан вар kw
        in_array($_GET['nagr'], [91, 92, 93, 94, 95]) &&
        in_array($ai['kw_n'], [0, 1, 2, 3, 4]) &&
        $ai['klaskw'] > $ai['kw_n']
    ) {
        $ai['kw_n'] += 1;
        $u->rangup($u->info['id'], $ai['kw_n'], 'kw');
        $i = 0;
        while ($i < $achievement_data['kw']['prize'][$ai['kw_n']]) {
            $u->addItem(4917, $u->info['id'], '');
            $i++;
        }
        $nagrtxt .= 'Клановый опыт +50000 X' . $achievement_data['kw']['prize'][$ai['kw_n']];
    } elseif ( //Башня смерти задание bs
        in_array($_GET['nagr'], [101, 102, 103, 104, 105]) &&
        in_array($ai['bs_n'], [0, 1, 2, 3, 4]) &&
        $ai['klasbs'] > $ai['bs_n']
    ) {
        $ai['bs_n'] += 1;
        $u->rangup($u->info['id'], $ai['bs_n'], 'bs');
        Db::sql('update users set money2 = money2 + ? where id = ?',
            [$achievement_data['bs']['prize'][$ai['bs_n']], $u->info['id']]);
        $nagrtxt .= $achievement_data['bs']['prize'][$ai['bs_n']] . $achievement_data['bs']['prize'][0];
    } elseif ( //Турниры победы trn
        in_array($_GET['nagr'], [111, 112, 113, 114, 115]) &&
        in_array($ai['trn_n'], [0, 1, 2, 3, 4]) &&
        $ai['klastrn'] > $ai['trn_n']
    ) {
        $ai['trn_n'] += 1;
        $u->rangup($u->info['id'], $ai['trn_n'], 'trn');
        Db::sql('update users set money2 = money2 + ? where id = ?',
            [$achievement_data['trn']['prize'][$ai['trn_n']], $u->info['id']]);
        $nagrtxt .= $achievement_data['trn']['prize'][$ai['trn_n']] . $achievement_data['trn']['prize'][0];
    }

    Db::sql('insert into chat (new, city, room, login, `to`, `text`, `time`, type, toChat) values (?,?,?,?,?,?,?,?,?)',
        [1, $u->info['city'], $u->info['room'], $u->info['login'], $nagrtxt, -1, 6, 0]);
    //-------------
}
function drawSunduk($nagr, $whatInside, $tier)
{
    return vsprintf('<img onclick="%s" onmouseover="%s" onmouseout="%s" onmousedown="%s" class="cp" src="%s" alt="Сундук">',
        [
            "location.href='\main.php?titul&nagr=$nagr'",
            "top.hi(this, '<b>Сундук $tier ранга<hr>Содержит:<hr> $whatInside</b>', event, 2, 0, 1, 1, 'max-width:307px')",
            "top.hic();",
            "top.hic();",
            "https://img.new-combats.com/i/titul/nagr$tier.gif"
        ]);
}

$data = null;
foreach ($achievement_data as $key => $value) {
    $data .= '<h4>' . $ai['name' . $key] . '</h4>';
    $data .= '<strong>' . $value[$key]['quest'] . '</strong>';
    $data .= 'Сейчас у Вас Ранг: <strong>' . $ai['klas' . $key] . '</strong>';
    $data .= 'Количество выполнений: <strong>' . $ai[$key] . ' =' . $ai['klasP' . $key] . '%</strong>';
    $data .= table([
        [TIERS, 1, 2, 3, 4, 5],
        $value[$key]['check'],
        array_merge([PRIZE], $value[$key]['prize'])
    ], 'prizelist', true);
    # If has new tier, AND only first 5 tiers AND prize is set.
    if (
        $ai['klas' . $key] > $ai[$key . '_n'] &&
        in_array($ai[$key . '_n'], [0, 1, 2, 3, 4]) &&
        !empty($value[$key]['prize']) &&
        !empty($value[$key]['startlink'])
    ) {
        $data .= '<br>' . PRIZE . ':<br>';
        if (in_array($value[$key]['prize'][0], ['екр.', 'кр.'])) {
            $sundukName = $value[$key]['prize'][$ai[$key . '_n'] + 1] . $value[$key]['prize'][0];
        } else {
            $sundukName = $value[$key]['prize'][0] . $value[$key]['prize'][$ai[$key . '_n'] + 1];
        }

        $data .= drawSunduk(
            $ai[$key . '_n'] + $value[$key]['startlink'],
            $sundukName,
            $ai[$key . '_n'] + $value[$key]['startlink']
        );
    }
    $data .= '<hr>';
}
?>

<style>
    /* for table() function */
    table.prizelist {
        border-spacing: 1px;
        border-collapse: separate;
        min-width: 500px;
    }

    table.prizelist tr {
        background-color: #C7C7C7;
    }

    table.prizelist td {
        padding: 3px;
        text-align: center;
    }

    table.prizelist td:first-child {
        width: 100px;
    }

    table.prizelist tr:first-child,
    table.prizelist td:first-child {
        background-color: #a5a5a5;
    }
</style>

<div style="text-align: right;">
    <input class="btn" type="button" value="Подсказка"
           onclick="window.open('/encicl/help/titul.html', 'help', 'height=300,width=500,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes')">
    <input class="btn" type="button" value="Вернуться" onClick="top.frames['main'].location = 'main.php';" name=edit>
</div>

<H3>Достижения</H3>

<?= $data;
unset($data);