<?php

use Battles\Bank;
use Battles\GameConfigs;
use Battles\Rooms;
use Battles\Template;
use Exceptions\GameException;
use Battles\User;

require_once "functions.php";
const SUCCESS = "Успешная операция!";

$bank = new Bank(User::getInstance()->getId());
$status = '';

$toid = $_POST['to_id'] ?? 0;
$summa = $_POST['summa'] ?? 0;
$submit = $_POST['action'] ?? '';
try {
// Зачисление кредитов на счёт.
    if ($submit === 'depositMoney' && $summa) {
        $operation = $bank->depositMoney($summa);
        User::getInstance()->setMoney($operation['walletMoney']);
        $bank->setMoney($operation['bankMoney']);
        $status = SUCCESS;
    }
// Снятие кредитов со счёта.
    if ($submit === 'withdrawMoney' && $summa) {
        $operation = $bank->withdrawMoney($summa);
        User::getInstance()->setMoney($operation['walletMoney']);
        $bank->setMoney($operation['bankMoney']);
        $status = SUCCESS;
    }
// Перевод кредитов на другой счёт.
    if ($submit === 'sendMoney' && $summa && $toid) {
        User::getInstance()->setMoney($bank->sendMoney($toid, $summa));
        $status = SUCCESS;
    }
} catch (GameException $e) {
    echo 'Банковская ошибка!';
} finally {
    unset($submit, $summa, $toid);
}
Template::header('Банк');
?>
<link href="css/secondary.css" rel="stylesheet"/>
<script src="js/main.js"></script>
<?php Template::buildingTop(Rooms::$roomNames[29], 'strah') ?>
<div><?= $status ?></div>
<div class="appblock appblock-main">
    <span class="wrap">На счету: <span class="num"><?= $bank->getMoney() ?></span></span>
    <hr>
    <span class="wrap">На руках: <span class="num"><?= User::getInstance()->getMoney() ?></span></span>
</div>
<div class="appblock">
    <span class="legend">Работа со счётом</span>
    <form method="post">
        <input size="10" name="summa" placeholder="Сумма">
        <input type="hidden" name="action" value="depositMoney">
        <input type="submit" value="Положить деньги">
    </form>
    <form method="post">
        <input size="10" name="summa" placeholder="Сумма">
        <input type="hidden" name="action" value="withdrawMoney">
        <input type="submit" value="Снять деньги">
    </form>
</div>
<div class="appblock">
    <span class="legend">Перевод кредитов</span>
    <form method="post">
        <input size="10" name="summa" placeholder="Сумма">
        <input size="10" name="to-id" placeholder="Cчёт"><br>
        <input type="hidden" name="action" value="sendMoney">
        <input type="submit" value="Перевести кредиты">
    </form>
    <span class="wrap">Комиссия: <?= GameConfigs::BANK_COMISSION * 100 ?>% от переводимой суммы, но не менее 1 кр.</span>
</div>
