<?php
// Устанавливаем время выполнения скрипта
$start_time = microtime();
$start_array = explode(" ",$start_time);
$start_time = $start_array[1] + $start_array[0];

include_once('connect.php');    // Подключаем БД
include_once('functions.php');  // Подключаем функции

// Обьявляем массив с настройками
$systema = mysql_query("SELECT * FROM `settings`");
$set = array();
while ($query = mysql_fetch_array($systema)) $set[$query[0]] = $query[1];

// Случайный набор символов
$gets = '';
// $gets = rand(1000,9999);

// Узнаем ip посетителя
if(!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else $ip = $_SERVER['REMOTE_ADDR'];

// Обьявляем переменные
$id = num($_GET["id"]);
$id2 = num($_GET["id2"]);
$type = num($_GET["type"]);
$page = num($_GET['page']);
$ref = num($_GET['r']);

$sort = filter($_GET['sort']);
$act = filter($_GET["act"]);
$act2 = filter($_GET["act2"]);

if(intval($_GET['otvet']) != 0){
	if(mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `id` = ".intval($_GET['otvet'])."")) != 0) $otv = intval($_GET['otvet']);
}
else $otv = 0;

// Завершаем задачи
if(mysql_num_rows(mysql_query("SELECT * FROM `tasks` WHERE `time_end` <= ".time()."")) != 0){
	$tasks = mysql_query("SELECT * FROM `tasks` WHERE `time_end` <= ".time()." ORDER BY `time_end` DESC");
	while($task = mysql_fetch_array($tasks)){
		if($task['work'] == 1) mysql_query("UPDATE `buildings` SET `status`= 'builted', `level` = 1,`zdorov` = 100 WHERE `country` = ".$task['country']." AND `type` = ".$task['work_type']."");
		else if($task['work'] == 2) mysql_query("UPDATE `buildings` SET `zdorov` = 100 WHERE `country` = ".$task['country']." AND `type` = ".$task['work_type']."");
		else if($task['work'] == 3) mysql_query("UPDATE `buildings` SET `level` = (`level` + 1) WHERE `country` = ".$task['country']." AND `type` = ".$task['work_type']."");
        else if($task['work'] == 6){
        	if($task['work_type'] == 3) mysql_query("UPDATE `voiska` SET `strelki` = (`strelki` + ".$task['kolvo']."), `strelki_free` = (`strelki_free` + ".$task['kolvo'].") WHERE `country` = ".$task['country']."");
        	else if($task['work_type'] == 2) mysql_query("UPDATE `voiska` SET `kavaleria` = (`kavaleria` + ".$task['kolvo']."), `kavaleria_free` = (`kavaleria_free` + ".$task['kolvo'].") WHERE `country` = ".$task['country']."");
        	else mysql_query("UPDATE `voiska` SET `pehota` = (`pehota` + ".$task['kolvo']."), `pehota_free` = (`pehota_free` + ".$task['kolvo'].") WHERE `country` = ".$task['country']."");
        }
        else if($task['work'] == 7) mysql_query("UPDATE `countries` SET `academics` = (`academics` + ".$task['kolvo']."), `academics_free` = (`academics_free` + ".$task['kolvo'].") WHERE `id` = ".$task['country']."");

		mysql_query("INSERT INTO `journal` SET `country` = ".$task['country'].", `type` = 1, `num1` = ".$task['work'].", `num2` = ".$task['work_type'].", `num3` = ".$task['kolvo'].", `time` = ".$task['time_end']."");
		mysql_query("UPDATE `countries` SET `".$task['mans']."_free`= (`".$task['mans']."_free` + ".$task['number'].") WHERE `id` = ".$task['country']."");
		mysql_query("DELETE FROM `tasks` WHERE `id` = ".$task['id']."");
	}
}

// Проверка куков авторизованного пользователя
if(isset($_COOKIE['id']) AND isset($_COOKIE['password']) ){
	$user_isset = mysql_query("SELECT * FROM `users` WHERE `id`='".intval($_COOKIE['id'])."' AND `password`='".mysql_real_escape_string(nl2br(htmlspecialchars(trim($_COOKIE['password']))))."'");
	if(mysql_num_rows($user_isset) > 0){
		$user = mysql_fetch_array($user_isset);
		if((time() - $user['time_last']) <= 30 AND $user['time_last'] < time()) mysql_query("UPDATE `users` SET `time_last`=".time().", `time_online` = (`time_online` + ".(time() - $user['time_last']).") WHERE `id` = '".$user['id']."'");
		else mysql_query("UPDATE `users` SET `time_last`=".time().",`ip` = '".$ip."' WHERE `id` = '".$user['id']."'");
		if($user['country'] != 0){
			$country = mysql_fetch_array(mysql_query("SELECT * FROM `countries` WHERE `id`=".$user['country']));
			if(mysql_num_rows(mysql_query("SELECT * FROM `voiska` WHERE `country`=".$country['id'])) == 0) mysql_query("INSERT INTO `voiska` SET `country` = ".$country['id']."");
			$voiska = mysql_fetch_array(mysql_query("SELECT * FROM `voiska` WHERE `country`=".$country['id']));
		}
	}
}

// Пользовательские настройки
if($user){
	$set['images'] = $user['images'];
	$set['background'] = $user['background'];
}

// Показ удаленых данных
if($user AND $user['level'] >= 2){
	$deleted = '';
	$wdeleted = '';
}
else{
	$deleted = ' AND `deleted` = 0 ';
	$wdeleted = ' WHERE `deleted` = 0 ';
}

// Вывод ошибок
include_once('errors.php');
?>