<?php

require_once("connect.inc.php");

function getFlags( $xCentre, $yCentre, $width, $height, $caseSize )
{
	global $connexion;
	
// calcul du rectangle de coordonnees --------------------------------------------------
	
	$width2  = abs($width/2);
	$height2 = abs($height/2);
	
	$xMin = $xCentre - $width2;
	$xMax = $xCentre + $width2;
	$yMin = $yCentre - $height2;
	$yMax = $yCentre + $height2;

// requete SQL --------------------------------------------------------------------------

$req = '
SELECT x, y, uid, emblem, master_id,
       user_guild_emblem as guild_emblem,
       user_guild_name   as guild_name
FROM (
      SELECT x, y, uid,
             user_guild_emblem    as emblem,
             user_guild_master_id as master_id 
      FROM (
	  
			SELECT ground_pos[0] AS x,
				   ground_pos[1] AS y,
				   user_id       AS uid
			FROM grounds 
			WHERE ground_pos[0] >= '.$xMin.' 
			AND   ground_pos[0] <  '.$xMax.'
			AND   ground_pos[1] >= '.$yMin.'
			AND   ground_pos[1] <  '.$yMax.'
      ) AS g JOIN users
      ON users.user_id = g.uid
) AS gu JOIN users 
ON users.user_id = gu.master_id
';

	$res = pg_query($connexion, $req) or die( pg_last_error().'<br />'.$req );
	$flags = '';
	while( $f = pg_fetch_array($res) )
	{
		$pos = 'style="left:'.($f['x']-$xMin)*$caseSize.'px; top:'.($f['y']-$yMin)*$caseSize.'px;"';
		$flags .= '<img src="'.$f['guild_emblem'].'" '.$pos.' alt=""/>
';
	}
	echo $flags;
}
//getFlags( 0, 0, 8, 8, 56, 1 );
getFlags( $_GET['x'], $_GET['y'], $_GET['w'], $_GET['h'], $_GET['caseSize'] );
?>