<?php
define('DB_HOST', 'localhost'); // Сервер
define('DB_NAME', '79998786090'); // Имя базы
define('DB_USER', '79998786090'); // Пользователь
define('DB_PASS', '1122334455'); // Пароль
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=UTF8", DB_USER, DB_PASS);

$array_end = [
    'diamond' => 1, // Алмаз
    'exp' => 100, // Опыт
    'gold' => 10 // Золото
];
$place = [
    1 => [
        'gold' => 1000,
        'exp' => 1000,
        'diamond' => 100,
    ],
    2 => [
        'gold' => 600,
        'exp' => 600,
        'diamond' => 60,
    ],
    3 => [
        'gold' => 300,
        'exp' => 300,
        'diamond' => 30,
    ]
];

$bonus = [
    'gold' => 0,
    'exp' => 0,
    'diamond' => 0,
];

$text = 'Вторжение окончено. Вы заняли ';
if ($db->query("SELECT COUNT(*) FROM `demons_battles` WHERE `status` = 'end'")->fetchColumn() == true) {

    $userList = $db->query("SELECT `damage`, `id_user` FROM `demons_players` ORDER BY `damage` DESC")->fetchAll();


    $queryInsert = $db->prepare("UPDATE users SET gold = gold + ?, exp = exp + ?, almaz = almaz + ? WHERE id = ?");
    $i = 1;
    foreach ($userList as $item) {

        $multiplication = floor($item['damage'] / 10000);

        if ($multiplication == true) {


            if ($i == 1 || $i == 2 || $i == 3) {
                $bonus = $place[$i];
            }

            $gold = $array_end['gold'] * $multiplication + $bonus['gold'];
            $exp = $array_end['exp'] * $multiplication + $bonus['exp'];
            $diamond = $array_end['diamond'] * $multiplication + $bonus['diamond'];
            $text .= $i . ' место и получили: ' . $gold . ' <img src="/images/icons/gold.png" width="20" />, ' . $exp . '  <img src="/images/icons/exp.png" width="20" /> и ' . $diamond . ' <img src="/images/icons/almaz.png" width="20" />.';

            if ($i == 1 || $i == 2 || $i == 3) {
                $text .= ' Дополнительная награда за ' . $i . ' место: ' . $bonus['gold'] . ' <img src="/images/icons/gold.png" width="20" />, ' . $bonus['exp'] . '  <img src="/images/icons/exp.png" width="20" /> и ' . $bonus['diamond'] . ' <img src="/images/icons/almaz.png" width="20" />';
            }

            $queryInsert->execute([$gold, $exp, $diamond, $item['id_user']]);

            if ($db->query("SELECT COUNT(*) FROM `kont` WHERE `id_user` = '1' && `id_kont` = '" . $item['id_user'] . "' LIMIT 1")->fetchColumn() == false) {
                $db->exec("INSERT INTO `kont` SET `id_user` = '1', `id_kont` = '" . $item['id_user'] . "', `time` = '" . time() . "'");
            }
            $db->exec("INSERT INTO `mai` SET `in` = '1', `out` = '" . $item['id_user'] . "', `text` = '$text' , `time` = '" . time() . "'");
        }
        $i ++;

    }
    $db->exec("TRUNCATE avenax_demon_chat");
    $db->exec("TRUNCATE demons_battles");
    $db->exec("TRUNCATE demons_players");
}