<?php
defined('_CONSTANT_') or die('Error. You don`t have permision to access.');
session_start();
ob_start();

require_once 'function.php';
require_once inc . 'class/Filter.php';
require_once inc . 'class/Count.php';
require_once inc . 'class/Nav.php';
require_once inc . 'class/User.php';
require_once inc . 'class/Browser.php';

$Filter = new Filter;
$Count = new Count;
$User = new User;

# Authorization;
if (empty($_SESSION['id'])) 
{
    if (!empty($_COOKIE['login']) && !empty($_COOKIE['password'])) 
    {
        $login    = $Filter->clearString($_COOKIE['login']);
        $password = $Filter->clearString($_COOKIE['password']);
        $sql      = DB::$dbs->queryFetch("SELECT `id` FROM ".USERS." WHERE `login` = ? && `password` = ?", [$login, $password]);

        if ($sql) 
        {
            $_SESSION['id'] = $Filter->clearInt($sql['id']);
        }
    } 
}

if (isset($_SESSION['id'])) 
{
    $user = DB::$dbs->queryFetch("SELECT * FROM ".USERS." WHERE `id` = ? LIMIT 1", [$_SESSION['id']]);

    if (!$user) 
    {
        unset($_SESSION['id']); 
        header("Location: ".HOME."/");
    }

    if (!empty($user) && $user['access'] == 2) 
    {
        genTimerStart();
    }

    # User online time;
    if (($user['last_time'] + 1) < time()) 
    {
        if ($user['last_time'] > (time() - 600)) 
        {
            $plusTime = time() - $user['last_time'];
        } 
        else 
        {
            $plusTime = NULL;
        }
        DB::$dbs->query("UPDATE ".USERS." SET `online_time` = ? WHERE `id` = ?", [($user['online_time'] + $plusTime), $user['id']]);
    }

    # Browser/ip;
    $browser   = new Browser();
    $userAgent = $browser->getBrowser() . ' (Версия: ' .  $browser->getVersion() . ')';
    $ip        = getIP();

    if ($user['browser'] != $userAgent) 
    {
        DB::$dbs->query("UPDATE ". USERS ." SET `browser` = ? WHERE `id` = ? LIMIT 1", [$userAgent, $user['id']]);
    } 

    if ($user['ip'] != $ip) 
    {
        DB::$dbs->query("UPDATE ". USERS ." SET `ip` = ? WHERE `id` = ? LIMIT 1", [$ip, $user['id']]);
    }
    DB::$dbs->query("UPDATE ".USERS." SET `last_time` = ? WHERE `id` = ? LIMIT 1", [time(), $_SESSION['id']]);
}

# Switch filter;
if (isset($_GET['do'])) 
{
    $do = $Filter->clearFullSpecialChars($_GET['do']); 
} 
else 
{
    $do = NULL;
} 

/* 

helmet 

cost 50

str 1 

defend 20

health20

*/