<?php
$dostup_country = true; // Проверка наличия государства
include_once('../inclfiles/core.php');

if($id != null){
	$all = mysql_num_rows(mysql_query("SELECT * FROM `tasks` WHERE `id` = ".$id." AND `country` = ".$country['id'].""));
	if($all != 0){
		$task = mysql_fetch_array(mysql_query("SELECT * FROM `tasks` WHERE `id` = ".$id." AND `country` = ".$country['id'].""));
		$procents = ((time() - $task['time_start']) / ($task['time_end'] - $task['time_start'])) * 100;

		switch($task['work']){
			case 1:
	        	$building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type'].""));
	        	$title = 'Постройка '.$building['name_rp'];
	            $building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$building['type'].""));
	            $rab_max = ceil($building['time'] / $set['built_time_max']);
			break;
			case 2:
	        	$building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type'].""));
	        	$title = 'Ремонт '.$building['name_rp'];
	            $building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$building['type'].""));
			break;
			case 3:
	        	$building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type'].""));
	        	$next_building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type']." AND `level` = ".($building['level'] + 1).""));
	        	$building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$building['type'].""));
	        	$title = 'Улучшение сооружения '.$building_type['name_rp'];
	            $rab_max = ceil($next_building['time'] / $set['built_time_max']);
			break;
			case 4:

			break;
			case 5:

			break;
			case 6:
				if($task['work_type'] == 3){
					$name_one = 'стрелка';
					$name_two = 'стрелков';
					$time_one = 1400;
				}
				else if($task['work_type'] == 2){
					$name_one = 'кавалериста';
					$name_two = 'кавалеристов';
					$time_one = 1000;
				}
				else{
					$name_one = 'пехотинца';
					$name_two = 'пехотинцев';
					$time_one = 800;
				}
				$title = 'Обучение '.chislo($task['kolvo'],$name_one,$name_two,$name_two);
			break;
			case 7:
               	$title = 'Обучение '.chislo($task['kolvo'],'ученого','ученых','ученых');
			break;
        }

		include_once('../inclfiles/head.php');

		if($_POST['plus'] != null OR $_POST['minus'] != null){
			$number = num($_POST['number']);

			if($task['mans'] == 'peoples'){
				$mans = 'рабочие';
				$mans_rp = 'рабочих';
			}
			else{
				$mans = 'ученые';
				$mans_rp = 'ученых';
			}

			if($number == 0) $err[] = 'Не введено количество '.$mans_rp;
			else{
	            if($_POST['plus'] != null){
             		if($number > $country[$task['mans'].'_free']) $err[] = 'Недостаточно свободных'.$mans_rp;
             		else{
	                	if($task['work'] == 1){
							if($number + $task['number']  > $rab_max) $err[] = 'Данное сооружение не могут строить столько '.$mans_rp;
                         	else $newtime = $building['time']/($number + $task['number']);
	                	}

	                	if($task['work'] == 2){
	                		$live = (100 - $building['zdorov'])/100;
							$newtime = floor($building['time']/($number + $task['number'])*$live);
	                	}

	                	if($task['work'] == 3){
	                		if($number + $task['number']  > $rab_max) $err[] = 'Данное сооружение не могут улучшать столько '.$mans_rp;
                         	else $newtime = floor($next_building['time']/($number + $task['number']));
	                	}

	                	if($task['work'] == 6){
	                		$newtime = floor($time_one/($number + $task['number']));
	                	}

	                	if($task['work'] == 7){
	                		$newtime = floor(900/($number + $task['number']));
	                	}


	                	if(!isset($err)){
	                	    $task['time_end'] = time() + floor((1-($procents/100)) * $newtime);
	                	    $task['time_start'] = time() - floor(($procents/100) * $newtime);
	                	    $task['number'] = $task['number'] + $number;
                            mysql_query("UPDATE `tasks` SET `time_end` = ".$task['time_end'].",`time_start` = ".$task['time_start'].",`number` = (`number` + ".$number.") WHERE `id` = ".$id." AND `country` = ".$country['id']."");
                            mysql_query("UPDATE `countries` SET `".$task['mans']."_free`= (`".$task['mans']."_free` - ".$number.") WHERE `id` = ".$country['id']."");
	                		if($task['mans'] == 'peoples'){
	                			m(chislo_word('Добавлен','Добавлено',$number,'рабочий','рабочих','рабочих'));
	                			$country['peoples_free'] = $country['peoples_free'] - $number;
	                		}
	                		else{
	                			m(chislo_word('Добавлен','Добавлено',$number,'ученый','ученых','ученых'));
	                			$country['academics_free'] = $country['academics_free'] - $number;
	                		}
	               		}
					}
	            }
	            else{
					if($number > $task['number']) $err[] = 'Над данной задачей работает меньшее число '.$mans_rp;
     				else{
           				if($number == $task['number']){
           					if($task['work'] == 1) mysql_query("DELETE FROM `buildings` WHERE `country` = ".$task['country']." AND `type` = ".$task['work_type']." AND `status` = 'built'");
           					if($task['work'] == 6 OR $task['work'] == 7) mysql_query("UPDATE `countries` SET `peoples_free`= (`peoples_free` + ".$task['kolvo']."),`peoples`= (`peoples` + ".$task['kolvo'].") WHERE `id` = ".$country['id']."");
      						mysql_query("UPDATE `countries` SET `".$task['mans']."_free`= (`".$task['mans']."_free` + ".$number.") WHERE `id` = ".$country['id']."");
                            mysql_query("DELETE FROM `tasks` WHERE `id` = ".$task['id']."");
                            t('Отозваны все '.$mans.'. Задача завершена');
	                		a('index.php?','Все задачи','tasks');
							a('new_task.php?','Новая задача','add');
	                		include_once('../inclfiles/foot.php');
           				}
           				else{

							if($task['work'] == 1){
								$newtime = $building['time']/($task['number'] - $number );
							}
							else if($task['work'] == 2){
	                			$live = (100 - $building['zdorov'])/100;
								$newtime = floor($building['time']/($number + $task['number'])*$live);
	                		}
							else if($task['work'] == 3){
	                			$newtime = floor($next_building['time']/($task['number'] - $number));
	             			}
							else if($task['work'] == 4){

	             			}
	             			else if($task['work'] == 5){

	             			}
							else if($task['work'] == 6){
	                			$newtime = floor($time_one/($task['number'] - $number));
	             			}
	             			else if($task['work'] == 7){
	                			$newtime = floor(900/($task['number'] - $number));
	             			}


                 			$task['time_start'] = time() - floor(($procents/100) * $newtime);
							$task['time_end'] = time() + ((1-floor($procents/100)) * $newtime);
	                	    $task['number'] = $task['number'] - $number;
                            mysql_query("UPDATE `tasks` SET `time_end` = ".$task['time_end'].",`time_start` = ".$task['time_start'].",`number` = (`number` - ".$number.") WHERE `id` = ".$id." AND `country` = ".$country['id']."");
	                		mysql_query("UPDATE `countries` SET `".$task['mans']."_free`= (`".$task['mans']."_free` + ".$number.") WHERE `id` = ".$country['id']."");
	                		if($task['mans'] == 'peoples'){
	                			m(chislo_word('Отозван','Отозвано',$number,'рабочий','рабочих','рабочих'));
	                			$country['peoples_free'] = $country['peoples_free'] + $number;
	                		}
	                		else{
	                			m(chislo_word('Отозван','Отозвано',$number,'ученый','ученых','ученых'));
	                			$country['academics_free'] = $country['academics_free'] + $number;
	                		}
  	                	}
					}
	            }
            }
		}

		$procenti = floor(((time() - $task['time_start']) / ($task['time_end'] - $task['time_start'])) * 100);

        err();
        t1();
        if($task['work'] == 1) echo 'Тип сооружения: '.$building_type['name'].'<br/>';
        echo 'Осталось: '.period($task['time_end'] - time()).'<br/>';
        if($task['mans'] == 'peoples') echo chislo_word('Работает','Работают',$task['number'],'рабочий','рабочих','рабочих').'<br/>';
        else echo chislo_word('Работает','Работают',$task['number'],'ученый','ученых','ученых').'<br/>';
        echo 'Завершено на '.$procenti.'%';
        t2();

		if($task['work'] == 1){
			if($country['peoples_free'] >= $rab_max - $task['number']) $kolvo = $rab_max - $task['number'];
            else $kolvo = $country['peoples_free'];
		}

		if($task['work'] == 2){
			$kolvo = $country['peoples_free'];
		}

		if($task['work'] == 3){
			if($country['peoples_free'] >= $rab_max - $task['number']) $kolvo = $rab_max - $task['number'];
            else $kolvo = $country['peoples_free'];
		}

		if($task['work'] == 6 OR $task['work'] == 7){
			$kolvo = $country['academics_free'];
		}


        echo '<form method="POST" action="index.php?id='.$id.'&'.$gets.'">';
	    t1();
	    echo '<center>';
	    if($task['mans'] == 'peoples') echo 'Количество рабочих (у Вас '.chislo($country['peoples_free'],'свободный рабочий','свободных рабочих','свободных рабочих').'):<br/>';
	    else echo 'Количество ученых (у Вас '.chislo($country['academics_free'],'свободный ученый','свободных ученых','свободных ученых').'):<br/>';
	    echo '<input type="text" name="number" value="'.$kolvo.'"/><br/>';
	    if($task['work'] == 1) echo '<small>Строить данное сооружение могут не более '.chislo($rab_max,'рабочего','рабочих','рабочих').'</small><br/>';
	    if($task['work'] == 3) echo '<small>Улучшать данное сооружение могут не более '.chislo($rab_max,'рабочего','рабочих','рабочих').'</small><br/>';
	    echo '<input name="plus" type="submit" value="Добавить" /> <input name="minus" type="submit" value="Отозвать" />';
		echo '</center>';
		t2();
		echo '</form>';
		p('Если отозвать всех, задача будет отменена');
		a('index.php?','Все задачи','tasks');
	}
	else{
    	$title = 'Ошибка';
		include_once('../inclfiles/head.php');
		t('Задача не найдена. Возможно, она уже была завершена раннее.');
		a('index.php?','Все задачи','tasks');
		a('new_task.php?','Новая задача','add');
	}
}
else{
	$title = 'Выполняющиеся задачи';
	include_once('../inclfiles/head.php');
	$all = mysql_num_rows(mysql_query("SELECT * FROM `tasks` WHERE `country` = ".$country['id'].""));
	if($all != 0){
		$tasks = mysql_query("SELECT * FROM `tasks` WHERE `country` = ".$country['id']." ORDER BY `time_end` ASC");
		while($task = mysql_fetch_array($tasks)){
			$procents = floor(((time() - $task['time_start']) / ($task['time_end'] - $task['time_start'])) * 100);

			switch($task['work']){
				case 1:
					$building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type'].""));
		   			$name = 'Постройка '.$building['name_rp'];
				break;
				case 2:
					$building = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_all` WHERE `type` = ".$task['work_type'].""));
		   			$name = 'Ремонт '.$building['name_rp'];
				break;
				case 3:
					$building_type = mysql_fetch_array(mysql_query("SELECT * FROM `buildings_types` WHERE `id` = ".$task['work_type'].""));
		   			$name = 'Улучшение сооружения '.$building_type['name_rp'];
				break;
				case 4:
					//тут ничего :(
				break;
				case 5:
                	//тут тоже :(
				break;
				case 6:
		            if($task['work_type'] == 3){
	         	    	$name_one = 'стрелка';
	         	    	$name_two = 'стралков';
	         	    }
	         	    else if($task['work_type'] == 2){
	         	    	$name_one = 'кавалериста';
	         	    	$name_two = 'кавалеристов';
	         	    }
	         		else{
	         	    	$name_one = 'пехотинца';
	         	    	$name_two = 'пехотинцев';
	         		}
		   			$name = 'Обучение '.chislo($task['kolvo'],$name_one,$name_two,$name_two);
				break;
				case 7:
		   			$name = 'Обучение '.chislo($task['kolvo'],'ученого','ученых','ученых');
		   		break;
	        }

			if($task['mans'] == 'peoples') $mans = chislo_word('Работает','Работают',$task['number'],'рабочий','рабочих','рабочих');
			else if($task['mans'] == 'academics') $mans = chislo_word('Работает','Работают',$task['number'],'ученый','ученых','ученых');
	        a('index.php?id='.$task['id'].'&',$name.' ['.$procents.'%]<br/><small>Осталось '.period($task['time_end'] - time()).'<br/>'.$mans.'</small>','none');
		}
	}
	else t('В данный момент в Вашем государстве нет выполняющихся задач');
	a('new_task.php?','Новая задача','add');
}
include_once('../inclfiles/foot.php');
?>