<?php

use Battles\Bank;
use Battles\Database\Db;
use Battles\User;

require_once "functions.php";
if (!User::getInstance()->getClan() || User::getInstance()->getBattle()) {
    exit();
}
const PRICES = [
    'sleep15' => 20,
    'sleep30' => 20,
    'closebattle' => 100,
    'heal20' => 10,
    'heal35' => 25,
    'heal50' => 50,
    'travmoff' => 10,
    'attack' => 10,
    'bloodattack' => 25,
    'death' => 100,
    'comment' => 5,
    'openbattle' => 100,
    'reamdeath' => 50,
    'clone' => 25,
    'unclone' => 25,
];

$check_owner = Db::getInstance()->execute('select short_name from clans where owner_id = ?', User::getInstance()->getId())->fetchColumn();
$check_bonuses = Db::getInstance()->execute('select count(*) from clan_bonuses where short_name = ?', User::getInstance()->getClan())->fetchColumn();

if (User::getInstance()->getClan() !== $check_owner) {
    exit('Запрещено: Вы не глава клана.');
}
if (!$check_bonuses) {
    exit('Запрещено: Вашему клану нельзя покупать бонусы.');
}

function buy_bonus($name): bool
{
    $bank = new Bank(User::getInstance()->getId());
    if ($bank->getMoney() <= PRICES[$name]) {
        return false;
    }

    $query = sprintf('update clan_bonuses set %s = %s + 1 where short_name = ?', $name, $name);
    Db::getInstance()->execute($query, User::getInstance()->getClan());
    $bank->setMoney($bank->getMoney() - PRICES[$name]);
    return true;
}

echo !empty($_POST['type']) && buy_bonus($_POST['type']) ? 'success' : 'error';