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

if($id != null){
	if(mysql_num_rows(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$id."")) != 0){
		$building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$id.""));
  		$title = 'Ремонт сооружения '.$building_type['name_rp'].'';
		include_once('../inclfiles/head.php');
		if(mysql_num_rows(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$id."")) == 0){
        	t('В Вашем государстве нет сооружения данного типа');
        	a('remont.php?','Ремонтировать что-нибудь другое','remont');
        	include_once('../inclfiles/foot.php');
        }

        $building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `type` = ".$id.""));
        $building_all = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$id." AND `level` = ".$building['level'].""));

	    if($building['status'] == 'built') $eerr = 'строится';
        else if($building['status'] == 'destroyed') $eerr = 'разрушено';
        else if($building['zdorov'] == 100) $eerr = 'не нуждается в ремонте';
        else if(mysql_num_rows(mysql_query("SELECT * FROM `tasks` WHERE `country` = ".$country['id']." AND `work` = 2 AND `work_type` = ".$id."")) > 0) $eerr = 'уже ремонтируется';
     	if($eerr != null){
			t('Сооружение данного типа '.$eerr);
			a('remont.php?','Ремонтировать что-нибудь другое','remont');
			include_once('../inclfiles/foot.php');
	    }


		$live = (100 - $building['zdorov'])/100;
		$building_all['money'] = floor($building_all['money']*$live);
		$building_all['wood'] = floor($building_all['wood']*$live);
		$building_all['stone'] = floor($building_all['stone']*$live);
		$building_all['iron'] = floor($building_all['iron']*$live);
		$building_all['oil'] = floor($building_all['oil']*$live);
		if($_POST['ok'] != NULL) {
			$kolvo_rab = abs(intval($_POST['kolvo_rab']));
			if(!res_proverka($building_all['money'],$building_all['wood'],$building_all['stone'],$building_all['iron'],0,$building_all['oil'],0)) $err[] = 'Недостаточно ресурсов';
			if($kolvo_rab == 0) $err[] = 'Не введено количество рабочих';
			if($kolvo_rab > $country['peoples_free']) $err[] = 'Недостаточно свободных рабочих';
            if (!isset($err)){
            	$ostalos = floor($building_all['time']/$kolvo_rab*$live);
                mysql_query("INSERT INTO `tasks` SET `work` = 2,`mans` = '".$work['mans']."', `country` = ".$country['id'].", `number` = ".$kolvo_rab.", `work_type` = ".$building_all['type'].",`time_start` = ".time().", `time_end` = ".(time() + $ostalos)."");
             	mysql_query("UPDATE `countries` SET `peoples_free`= (`peoples_free` - ".$kolvo_rab."), `money`= (`money` - ".$building_all['money']."), `wood`= (`wood` - ".$building_all['wood']."), `stone`= (`stone` - ".$building_all['stone']."), `iron`= (`iron` - ".$building_all['iron']."), `oil`= (`oil` - ".$building_all['oil'].") WHERE `id` = ".$country['id']." ");
				t('Ремонт сооружения успешно начат<br/>До завершения осталось: '.period($ostalos));
              	a('remont.php?','Ремонтировать еще что-нибудь','remont');
              	include_once('../inclfiles/foot.php');
            }
		}

		err();
  		t('Целостность: '.round($building['zdorov']).'%');
        res_nado('ремонта '.$building_all['name_rp'],$building_all['money'],$building_all['wood'],$building_all['stone'],$building_all['iron'],0,$building_all['oil'],0);

		if(res_proverka($building_all['money'],$building_all['wood'],$building_all['stone'],$building_all['iron'],0,$building_all['oil'],0)){
               if($country['peoples_free'] > 0){
              	 	echo '<form action="remont.php?id='.$id.'&'.$gets.'" method="POST">';
					c('Количество рабочих (у Вас '.chislo($country['peoples_free'],'свободный рабочий','свободных рабочих','свободных рабочих').'):<br/><input type="text" name="kolvo_rab" value="'.$country['peoples_free'].'"/><br/><input name="ok" type="submit" value="Ремонтировать" />');
					echo '</form>';
			}
			else t('У Вас нет свободных рабочих для ремонта');
		}
		else t('Недостаточно ресурсов для ремонта сооружения');
	}
	else{
		$title = 'Ошибка';
		include_once('../inclfiles/head.php');
		t('Данный тип сооружений не найден');
	}
	a('remont.php?','Ремонтировать что-нибудь другое','remont');
}
else{
	$title = $work['name'];
	include_once('../inclfiles/head.php');
    if(mysql_num_rows(mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `zdorov` < 100 AND `type` NOT IN (SELECT `work_type` FROM `tasks` WHERE `country` = ".$country['id']." AND `work` = 2)")) != 0){
		$buildings = mysql_query("SELECT * FROM `buildings` WHERE `country` = ".$country['id']." AND `zdorov` < 100 AND `type` NOT IN (SELECT `work_type` FROM `tasks` WHERE `country` = ".$country['id']." AND `work` = 2) ORDER BY `zdorov` 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="remont.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'].' ['.$building['zdorov'].'%]<br/><small>'.$building_type['name'].'</small></td></tr></table></a>';
        	else a('remont.php?id='.$building['type'].'&',$building_all['name'].' ['.$building['zdorov'].'%]<br/><small>'.$building_type['name'].'</small>','none');
		}
	}
	else t('В Вашем государстве нет сооружений, нуждающихся в ремонте');
}
a('new_task.php?','Добавление задач','add');
include_once('../inclfiles/foot.php');
?>