<?php

use Battles\{Database\Db, DressedItems, InventoryItem, Travel, User, UserInfo, UserEffect};
use Exceptions\GameException;

if (filter_input(INPUT_SERVER, 'QUERY_STRING') === 'exit') {
    //session_destroy();
    echo 'EXIT PRESSED';
    header("Location: fight.php");
}
require_once 'functions.php';

User::getInstance()->setOnline();

if (!empty($_GET['edit'])) {
    if (!empty($_GET['ups'])) {
        try {
            $up = new UserInfo(User::getInstance()->getId());
            $up->addOnePointToStat($_GET['ups']);
            unset($up);
        } catch (GameException $e) {
            echo $e;
        }
    }
    if (!empty($_GET['drop'])) {
        $items = new DressedItems(User::getInstance()->getId());
        $items->undressItem($_GET['drop']);
        unset($items);
    }
    //Пока что одеваем предмет отсюда.
    if (!empty($_GET['dress'])) {
        $dressing = new InventoryItem(Db::getInstance()->ofetch('select * from inventory where item_id = ? ', $_GET['dress']));
        $dressing->dressItem();
        unset($dressing);
    }
    //Выбросить предмет. Ниоткуда не вызывается. О_о
    if (!empty($_GET['destruct'])) {
        $item = new InventoryItem(Db::getInstance()->ofetch('select * from inventory where item_id = ? ', $_GET['destruct']));
        echo $item->drop();
        unset($item);
    }
    if (!empty($_GET['undress']) && $_GET['undress'] === 'all') {
        DressedItems::undressAllItems(User::getInstance()->getId());
    }
}

// Подготавливаем отображение инфы и предметов.
$data = Db::getInstance()->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', User::getInstance()->getId());
$iteminfo = [];
foreach ($data as $row) {
    $iteminfo = new InventoryItem($row);
}

//Обработчики нажатий на кнопки.
if (!empty($_POST['battlefield']) && User::getInstance()->getRoom() === 1) {
    header('Location: zayavka.php');
    exit();
}
if (!empty($_POST['module_quest'])) {
    header('Location: module_quest.php');
    exit();
}
if (!empty($_POST['move_inside']) && User::getInstance()->getRoom() === 20) {
    header('Location: main.php?goto=arena');
    exit();
}
if (!empty($_POST['move_outside']) && User::getInstance()->getRoom() === 1) {
    header('Location: main.php?goto=plo');
    exit();
}
if (!empty($_POST['main_page'])) {
    header('Location: main.php');
    exit();
}

if (empty($_GET['edit'])) {
    /* === проверяем соответствие комнаты и скрипта === */
    if (in_array(User::getInstance()->getRoom(), [20, 21, 26, 48, 51, 52, 651, 2655, 2601, 2701, 2702, 2111])) {
        header('Location: city.php');
        exit();
    }
    if (in_array(User::getInstance()->getRoom(), [22, 23, 25, 27, 29, 30, 31, 34, 45, 53, 61, 402, 403, 600, 601, 602, 603, 620, 621, 650, 660, 661, 662, 666, 760, 1051, 1052, 1055])) {
        header('location: ' . Travel::$roomFileName[User::getInstance()->getRoom()]);
        exit();
    }
}

// Входим и выходим если можем.
if (!empty($_GET['goto'])) {
    $imove = true;
    $isInjured = Db::getInstance()->fetchColumn('select count(*) from users_effects where owner_id = ? and (type = 14 or type = 13)') > 0;
    function gotoroom($room_id)
    {
        $query = 'update users, online set users.room = ' . '$room_id' . ', online.room = ' . '$room_id' . ' where user_id = id and user_id = ?';
        Db::getInstance()->execute($query, User::getInstance()->getId());
    }

    if (UserEffect::isOverEncumbered(User::getInstance()->getId())) {
        err('У вас переполнен рюкзак, вы не можете передвигаться...');
        $imove = false;
    }
    if ($isInjured) {
        err('У вас тяжелая травма, вы не можете передвигатся...');
        $imove = false;
    }
    if ($_GET['goto'] === 'plo' && !User::getInstance()->getZayavka() && $imove && User::getInstance()->getRoom() != 20) {
        Travel::toRoom(20, User::getInstance()->getRoom());
        Travel::roomRedirects(User::getInstance()->getRoom(), User::getInstance()->getBattle());
    } else {
        err('Подали заявку на бой и убегаете из клуба? Нехорошо...');
    }
    if ($_GET['goto'] === 'arena' && User::getInstance()->getRoom() == 20 && $imove) {
        Travel::toRoom(1, User::getInstance()->getRoom());
        Travel::roomRedirects(User::getInstance()->getRoom(), User::getInstance()->getBattle());
    }
}

if (!empty($_GET['obraz'])) {
    User::getInstance()->setShadow($_GET['obraz']);
    User::getInstance()->saveUser();
}

if (!empty($_POST['setshadow'])) {
    include_once 'views/main-setshadow.php';
    exit();
}

include_once 'views/main-game.php';