<?php
session_start();
include("serverConnect.php");
include("functions.php");

$displayError = true;

if (isset($_GET['territory']) && isset($_GET['building'])){
    //TODO : check everything
    
    $buildings = getBuildingsList();
    $buildingId = intval($_GET['building']);
    $territoryId = intval($_GET['territory']);
    
    $building = getBuildingsList()[$buildingId];
	
    $req = $bdd->prepare('INSERT INTO cBuildingConstructions (territory, type, timeFinished) VALUES(?, ?, ?)');
    $req->execute(array($territoryId, $buildingId, time() + $building["construction"]["time"]));

    
    $region = getRegionFromTerritory($territoryId);
    if (getRegionOwner($region) == 0) {
        addInfluenceInRegion($region, $_SESSION['id'], 0); //ensure that the influence for the user exists
        
        $req = $bdd->prepare('UPDATE cInfluences SET ' . $buildings[$buildingId]['influence']['column'] . ' = ? WHERE user = ? AND region = ?');
        $req->execute(array($territoryId, $_SESSION['id'], $region));
        
        $region = $_SESSION['capital'];
    }
    foreach ($building["construction"]["resources"] as $r => $amount) {
        removeResourcesInRegion($region, getResourceId($r), $amount);
    }
    
    $displayError = false;
}

if (!$displayError){
	header("Location:region.php");
	exit;
}
else {
    echo "FAIL";
}
?>