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

$displayError = true;

if (isset($_GET['id']) && isset($_GET['index'])){
    //TODO : check everything, maybe redo path search
    
    $offerId = intval($_GET['id']);
    $offerIndex = intval($_GET['index']);
    $regionId = intval($_SESSION['regionId']);
    
    $req = $bdd->prepare('SELECT * FROM cTradeOffers WHERE cTradeOffers.id = ?');
    $req->execute(array($offerId));
    if($data = $req->fetch()) {
        $req = $bdd->prepare('INSERT INTO cTransports (regionStart, regionEnd, resource, amount, timeArrived, time, way) VALUES(?, ?, ?, ?, ?, ?, ?)');
        $req->execute(array($data['region'], $regionId, $data['resource'], $data['amount'], time(), $_SESSION['tmpPath'][$offerIndex]["time"], 1));
        
        $req = $bdd->prepare('DELETE FROM cTradeOffers WHERE cTradeOffers.id = ?');
        $req->execute(array($offerId));
        
        mergeRegionSets($data['region'], $regionId);
        
        $displayError = false;
    }
}

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