<?php
ob_start();
$c_host = 'localhost';
$c_host = 'localhost';
$c_login = 'civa';
$c_pass = 'gsd12a';
$c_db = 'civa';
$link = mysql_connect($c_host, $c_login, $c_pass)
  or
die ("Не возможно присоединитса к Базе Данных. Сервер возможно перезагружаетса. Обновите страницу через пару секунд");

mysql_select_db ($c_db)
  or die ("Could not select database");
  mysql_query("SET NAMES 'windows-1251'", $link);
  mysql_set_charset("utf8");

header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: private");
header("Cache-Control: max-stale=0");
header("Content-type: text/html; charset=utf8");

  error_reporting(0);
$time = $_SERVER['REQUEST_TIME'];
$date = date('H:i:s',$time);
$dt=date("Y-m-d H:i:s");
$self=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

function send_mess($l_to,$what,$a,$b)
{
$whom=mysql_fetch_array(mysql_query("SELECT * FROM users WHERE login='$l_to'"));
	if($whom['login'] != "")
	{
$to_whom_id=$whom[id];
$when=date('G:i:s');
$login_send= $a;
$id_send=$b;
  $as=$time+5;
mysql_query("UPDATE users SET msg_send='$as' WHERE id='$id'");
mysql_query("
INSERT INTO `msg` (
`id` ,
`by_whom` ,
`by_whom_id` ,
`to_whom` ,
`to_whom_id` ,
`when` ,
`what` ,
`read`,
`input`,
`output`
)
VALUES (
NULL , '$login_send', '$id_send', '$l_to', '$to_whom_id', '$when', '$what', '0','1','1'
)
");
	}
}


$usql=mysql_query("SELECT * FROM users WHERE defeat='0'");
while($u=mysql_fetch_array($usql))
{


/*
	//прирост населения
*/

	$works=mysql_fetch_row(mysql_query("SELECT sum(workers) FROM `res_get` WHERE id_user='$u[id]'"));

	$add_people=abs(10+(($u['sc_arive']/100)*50));

    echo '[<u>'.$u[country].'</u>] <b>'.$tw.'</b> + '.$add_people.' = ';
	$vil=mysql_query("SELECT * FROM ubuildings WHERE sname='Village' AND owner_id='$u[id]'");
	if(mysql_num_rows($vil) == 1)
	{
		$v=mysql_fetch_array($vil);
		$max_people=$v['land']*3*(1+$u['sc_workers']/100);
		$itog_add = $add_people;
	} else
		{
		$max_people = 200;
		$itog_add = 0;
		}
		echo  $itog_add.'<br />';
	mysql_query("UPDATE users SET workers=workers+'$itog_add' WHERE id='$u[id]'");
	$text='Ваше население выросло на <b>'.$itog_add.'</b> человек! Максимальная плотность населения <b>'.$max_people.'</b> человек';
    send_mess($u['login'],$text,'Система','');


	if (!empty($u['ip']))
		{
    //Хавка)))
    $count_teach=mysql_fetch_row(mysql_query("SELECT sum(amount+sc) FROM `teach` WHERE id_user='$u[id]'"));//сума обучающихся солдат
    $count_work=mysql_fetch_row(mysql_query("SELECT sum(workers) FROM `res_get` WHERE id_user='$u[id]'"));
    $count_free=mysql_fetch_row(mysql_query("SELECT sum(workers+scientists+solders+horses+archers) FROM `users` WHERE id='$u[id]'"));
    $count_wars=mysql_fetch_row(mysql_query("SELECT sum(solders+horses+archers) FROM `wars` WHERE id_attacker='$u[id]'"));
    $food_need=intval(($count_teach[0]+$count_work[0]+intval(abs($count_free[0]*0.5))+$count_wars[0]));
	$total_people_chuma=intval(($count_teach[0]+$count_work[0]+$count_free[0]));
    if($u['grain'] > $food_need)
    {
	$grain_fooed_nedd = intval($u['grain']-$food_need);
    	mysql_query("UPDATE users SET grain='$grain_fooed_nedd' WHERE id='$u[id]' AND `ip`!='Неизвестно'");
    	$text='Ваше население употребило <b>'.$food_need.'</b> зерна!';
    	send_mess($u['login'],$text,'Система','');
    }
    else
    {
    	$k_show=abs(ceil($u['grain']*100/$food_need));
    	if($k_show > 70)
    	{
    		$k_show=70;
    	}
    	$k_lost=abs($k_show/100);
    	mysql_query("UPDATE users SET
    	workers=workers*'$k_lost',
    	scientists=scientists*'$k_lost',
    	solders=solders*'$k_lost',
    	horses=horses*'$k_lost',
		grain='0',
    	archers=archers*'$k_lost'
    	WHERE id='$u[id]'
    	");
    	mysql_query("UPDATE wars SET
    	solders=solders*'$k_lost',
    	horses=horses*'$k_lost',
    	archers=archers*'$k_lost'
    	WHERE id_attacker='$u[id]'");
    	mysql_query("
    	UPDATE res_get SET workers=workers*'$k_lost' WHERE id_user='$u[id]'
    	");
    	mysql_query("
    	UPDATE teach SET amount=amount*'$k_lost', sc=sc*'$k_lost' WHERE id_user='$u[id]'
    	");
    	$not_inaf=$food_need-$u['grain'];
    	$text='Вам не хватило <b>'.$not_inaf.'</b> зерна и <b>'.$k_lost.'</b>% вашего населения вымерло от голода!';
    	send_mess($u['login'],$text,'Система','');
    }
		} else
			{
			$text='Пустышки и боты жратву не едят';
			send_mess($u['login'],$text,'Система','');
			}

	//Сбежали рабы
	$b_derevn = mysql_fetch_array(mysql_query("SELECT * FROM `ubuildings` WHERE `sname`='Village' AND `owner_id`='$u[id]'"));
	if (($b_derevn[land]*6)<$u['workers'] AND $total_people_chuma < '12000')
					{

					$away_rab = round(0.13*$u['workers']);
					$text='Сбежало '.$away_rab.' рабочих';
					send_mess($u['login'],$text,'Система','');
					mysql_query("UPDATE `users` SET `workers`=workers-'$away_rab' WHERE `id`='$u[id]'");
					}



	//Катаклизмы
	if ($u['mountains'] > intval(2500+(15000*($u['sc_savem']/100))))
		{
		$proc_m = rand(20,70);
		$away_m = round(($proc_m/100)*$u['mountains']);
		$text='Из за землятресений вы потеряли '.$away_m.' гор';
		send_mess($u['login'],$text,'Система','');
		mysql_query("UPDATE `users` SET `mountains`=mountains-'$away_m', `land`=land+'$away_m' WHERE `id`='$u[id]'");
		}

	if ($u['woods'] > intval(2500+(15000*($u['sc_savew']/100))))
		{
		$proc_w = rand(20,70);
		$away_w = round(($proc_w/100)*$u['woods']);
		$text='Из за лесных пожаров вы потеряли '.$away_w.' леса';
		send_mess($u['login'],$text,'Система','');
		mysql_query("UPDATE `users` SET `woods`=woods-'$away_w', `land`=land+'$away_w' WHERE `id`='$u[id]'");
		}

	if ($total_people_chuma >= '12000')
		{

		$chuma_rand = rand(1,3);
		if ($total_people_chuma >= '15000') $chuma_rand = 1;
		if ($chuma_rand == 1)
			{
		$k_lost=abs((rand(70,90))/100);

    	mysql_query("UPDATE users SET
    	workers=workers*'$k_lost',
    	scientists=scientists*'$k_lost',
    	solders=solders*'$k_lost',
    	horses=horses*'$k_lost',
    	archers=archers*'$k_lost'
    	WHERE id='$u[id]'
    	");
    	mysql_query("UPDATE wars SET
    	solders=solders*'$k_lost',
    	horses=horses*'$k_lost',
    	archers=archers*'$k_lost'
    	WHERE id_attacker='$u[id]'");
    	mysql_query("
    	UPDATE res_get SET workers=workers*'$k_lost' WHERE id_user='$u[id]'
    	");
    	mysql_query("
    	UPDATE teach SET amount=amount*'$k_lost', sc=sc*'$k_lost' WHERE id_user='$u[id]'
    	");
    	$text='В вашем государстве эпидемия чумы. <b>'.intval($k_lost*100).'</b>% вашего населения вымерло от болезни!';
    	send_mess($u['login'],$text,'Система','');
			}
		}


	//Стареет генерал
	$gena = mysql_fetch_array(mysql_query("SELECT * FROM `general` WHERE `id_user`='$u[id]'"));
	if (!empty($gena['name']))
		{
		$age_gena = $gena['age']+1;
		mysql_query("UPDATE `general` SET `age`=age+'1' WHERE `id_user`='$u[id]'");
		if ($age_gena > '80')
			{
			$rand_dead = rand(1,10);
			if ($rand_dead >= 9)
				{
				$text='Ваш генерал прожил доблестных '.$age_gena.' года и скончался...';
				send_mess($u['login'],$text,'Система','');
				mysql_query("DELETE FROM `general` WHERE `id_user`='$u[id]'");
				} else
						{
						$text='В этом году, вашему генералу  исполнилось '.$age_gena.' года';
						send_mess($u['login'],$text,'Система','');
						}
			}
		}



	//Подарок
	mysql_query("UPDATE `users` SET `last_gift`='1' WHERE `id`='$u[id]'");


    //напряжение
    $new_unrest=$u['unrest']-(abs(intval($u['unrest']*0.25)));
    if($new_unrest < 0)
    {
    $new_unrest=0;
    }
    mysql_query("UPDATE users SET unrest='$new_unrest' WHERE id='$u[id]'");
    $text='Напряжение в стране упало на <b>'.abs(intval($u['unrest']*0.25)).'%</b>';
    send_mess($u['login'],$text,'Система','');



    	$woods_add=abs(rand(20,60)*$u['sc_wood']);
    	$max_wood=$u['sc_savew']*100;
    	$total_woods=$woods_add+$u['woods'];
    	if($total_woods > $max_wood)
    	{
		if ($u['lands'] < $woods_add)
			{
			$woods_add=0;
			} else {
    		$woods_add=$max_wood-$u['woods'];
    		if($woods_add < 0)
    		{
    			$woods_add=0;
    		}
				   }
    	}
    	mysql_query("UPDATE users SET woods=woods+'$woods_add', land=land-'$woods_add' WHERE id='$u[id]'");
    	$text='На ваших территориях выращено <b>'.$woods_add.'</b> нового леса';
    	send_mess($u['login'],$text,'Система','');


    	$mountains_add=abs(rand(200,600));
    	$max_mountains=$u['sc_savem']*100;
    	$total_mountains=abs($mountains_add+$u['mountains']);
    	if($total_mountains > $max_mountains)
    	{
			if ($u['lands'] < $woods_add)
			{
			$mountains_add=0;
			} else  {
    		$mountains_add=$max_mountains-$u['mountains'];
    		if($mountains_add < 0)
    		{
    			$mountains_add=0;
    		}
					}
    	}
    	$money_add=$u['mountains']*3;
    	mysql_query("UPDATE users SET money=money+'$money_add', mountains=mountains+'$mountains_add', land=land-'$mountains_add' WHERE id='$u[id]'");
    	$text='Найдены залежы гор. <b>+'.$mountains_add.'</b> горных пород';
    	send_mess($u['login'],$text,'Система','');
    	$text='Вы получили <b>'.$money_add.'</b> денег с горных пород';
    	send_mess($u['login'],$text,'Система','');

		if ($u['workers'] < '0') mysql_query("UPDATE `users` SET `workers`='0' WHERE `id`='$u[id]'");



}







?>