<?php
$dostup_country = true; // Проверка наличия государства
include_once('../inclfiles/core.php');
$work = mysql_fetch_array(mysql_query("SELECT * FROM `works` WHERE `id` = 1"));

if($id!=0){
	$all = mysql_num_rows(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$id." AND `level` = 1"));
	if($all != 0){
	    $building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$id." AND `level` = 1"));
	    $building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$id.""));
		$title = 'Постройка '.$building['name_rp'].'';
		include_once('../inclfiles/head.php');
		if(mysql_num_rows(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$building['type']." AND `status` <> 'destroyed'")) == 0){
            $rab_max = ceil($building['time'] / $set['built_time_max']);
  			if($_POST['ok'] != NULL) {
				$kolvo_rab = abs(intval($_POST['kolvo_rab']));
            	if(!res_proverka($building['money'],$building['wood'],$building['stone'],$building['iron'],0,$building['oil'],$building_type['territory'])) $err[] = 'Недостаточно ресурсов';
			    if($kolvo_rab == 0) $err[] = 'Не введено количество рабочих';
			    if($kolvo_rab > $country['peoples_free']) $err[] = 'Недостаточно свободных рабочих';
			    if($kolvo_rab > $rab_max) $err[] = 'Данное сооружение не могут строить столько рабочих';

                if (!isset($err)){
                    $ostalos = $building['time']/$kolvo_rab;
                    if(mysql_num_rows(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$building['type']." AND `status` = 'destroyed'")) > 0){
                        $destroyed_building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$building['type']." AND `status` = 'destroyed'"));
                        mysql_query("UPDATE `countries` SET `territory_free`= (`territory_free` + ".$destroyed_building['territory'].") WHERE `id` = ".$country['id']." ");
                        mysql_query("DELETE FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$building['type']." AND `status` = 'destroyed'");
                    }
                	mysql_query("INSERT INTO `tasks` SET `work` = 1,`mans` = '".$work['mans']."', `country` = ".$country['id'].", `number` = ".$kolvo_rab.", `work_type` = ".$building['type'].",`time_start` = ".time().", `time_end` = ".(time() + $ostalos)."");
                    mysql_query("UPDATE `countries` SET `peoples_free`= (`peoples_free` - ".$kolvo_rab."), `money`= (`money` - ".$building['money']."), `wood`= (`wood` - ".$building['wood']."), `stone`= (`stone` - ".$building['stone']."), `iron`= (`iron` - ".$building['iron']."),`oil`= (`oil` - ".$building['oil']."), `territory_free`= (`territory_free` - ".$building_type['territory'].") WHERE `id` = ".$country['id']." ");
					mysql_query("INSERT INTO `buildings` SET `country` = ".$country['id'].", `type` = ".$building['type'].", `level` = 1, `territory` = ".$building_type['territory']."");
                    t('Постройка сооружения успешно начата<br/>До завершения осталось: '.period($ostalos));
                	a('built.php?','Построить еще что-нибудь','built');
                	include_once('../inclfiles/foot.php');
                }
			}

			err();
            t('Тип сооружения: '.$building_type['name']);
            res_nado('постройки '.$building['name_rp'],$building['money'],$building['wood'],$building['stone'],$building['iron'],0,$building['oil'],$building_type['territory']);

			if(res_proverka($building['money'],$building['wood'],$building['stone'],$building['iron'],0,$building['oil'],$building_type['territory'])){
                if($country['peoples'] > 0){
               	 	if($country['peoples_free'] >= $rab_max) $kolvo = $rab_max;
                	else $kolvo = $country['peoples_free'];
					echo '<form action="built.php?id='.$id.'&'.$gets.'" method="POST">';
					c('Количество рабочих (у Вас '.chislo($country['peoples_free'],'свободный рабочий','свободных рабочих','свободных рабочих').'):<br/><input type="text" name="kolvo_rab" value="'.$kolvo.'"/><br/><small>Строить данное сооружение могут не более '.chislo($rab_max,'рабочего','рабочих','рабочих').'</small><br/><input name="ok" type="submit" value="Начать постройку" />');
					echo '</form>';
				}
				else t('У Вас нет свободных рабочих для постройки');
			}
			else t('Недостаточно свободной территории либо ресурсов для постройки данного сооружения');
		}
		else t('В Вашем государстве уже строится либо было построено данное сооружение');
	}
	else{
		$title = 'Ошибка';
		include_once('../inclfiles/head.php');
		t('Данное сооружение не найдено');
	}
	a('built.php?','Построить что-нибудь другое','built');
}
else{
	$title = $work['name'];
	include_once('../inclfiles/head.php');
    if(mysql_num_rows(mysql_query("SELECT * FROM `buildings_all` WHERE `level` = 1 AND `type` NOT IN (SELECT `type` FROM `buildings` WHERE `country`= ".$country['id']." AND `status` <> 'destroyed')")) != 0){
		$buildings = mysql_query("SELECT * FROM `buildings_all` WHERE `level` = 1 AND `type` NOT IN (SELECT `type` FROM `buildings` WHERE `country`= ".$country['id']." AND `status` <> 'destroyed') ORDER BY `id` ASC");
		while($building = mysql_fetch_array($buildings)){
			$building_all = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type`= ".$building['type']." AND `level` = ".$building['level'].""));
			$building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$building['type'].""));
			if($set['images'] == 'on') echo '<a class="building_link" href="built.php?id='.$building['type'].'&'.$gets.'"><table><tr><td class="building_left"><center><img src="/images/buildings/'.$building_all['id'].'.jpg" alt=""></center></td><td class="building_right">'.$building_all['name'].'<br/><small>'.$building_type['name'].'</small></td></tr></table></a>';
        	else a('built.php?id='.$building['type'].'&',$building_all['name'].'<br/><small>'.$building_type['name'].'</small>','none');
		}
	}
	else t('Нет доступных для сооружений для постройки');
}
a('new_task.php?','Добавление задач','add');
include_once('../inclfiles/foot.php');
?>