<?
function simulateRegionUntilConstruction($regionId, $until) {
	include("serverConnect.php");

	$buildings = getBuildingsList();

	do {
		$construction = true;

	    $req = $bdd->prepare('SELECT MIN(cBuildingConstructions.timeFinished) AS T FROM cBuildingConstructions WHERE territory >= ? AND territory <= ? ');
		$req->execute(array(getMinTerritoryId($regionId), getMaxTerritoryId($regionId)));
		$data = $req->fetch();

		$t = nullIsZero($data['T']);

		if ($t == 0 || $t > $until) {
		    $t = $until;
		    $construction = false;
		}

		$result = simulateRegion($regionId, $t);

		if ($construction) {
			$req = $bdd->prepare('SELECT * FROM cBuildingConstructions WHERE territory >= ? AND territory <= ? AND timeFinished = ?');
	        $req->execute(array(getMinTerritoryId($regionId), getMaxTerritoryId($regionId), $t));
	        
	        while ($data = $req->fetch()) {
	            $production = 0;
	            
	            if (array_key_exists("production", $buildings[$data['type']])) {
	                foreach ($buildings[$data['type']]["production"] as $key => $prod) {
	                    $production = getResourceId($key);
	                }
	            }
	            
	            $req2 = $bdd->prepare('INSERT INTO cBuildings (territory, type, production) VALUES(?, ?, ?)');
	            $req2->execute(array($data['territory'], $data['type'], $production));
	            
	            $req2 = $bdd->prepare('DELETE FROM cBuildingConstructions WHERE territory = ?');
	            $req2->execute(array($data['territory']));
	        }

		}
		
	} while ($t < $until);

	return $result;
}

?>