<?php
include_once("includes/user_data.php");
include_once("includes/classes/Affiliations.inc.php");
$Affiliations = new Affiliations($user_data['ID']);


if((int)$_POST['affiliation_ID']>0)
	if($_POST['action']=="add")
		if($Affiliations->addAffiliation((int)$_POST['affiliation_ID']))
			$success = "Added affiliation. You are now a member.";
		else
			$error = "Failed to add affiliation. Perhaps you're already a part of the group?";
	elseif($_POST['action']=="remove")
		if($Affiliations->removeAffiliation((int)$_POST['affiliation_ID']))
			$success = "Removed affilation. You are no longer a member.";
		else
			$error = "Inexplicable failure. Maybe not a part of the affiliation?";

include_once("includes/header.php");

?>


<h2>Your Affiliated Groups</h2>
<ul>
	<?php
	
	$affiliations = $Affiliations->getAffiliations();
	if(is_array($affiliations)){
		foreach($affiliations as $affiliation){
			?>
			<li>
				<?php
					if(strlen($affiliation['logo_url'])>5)
						echo "<img src='".$affiliation['logo_url']."'><br/>";
				?>
				<h3>
					<a href="=<?=$affiliation['url'];?>">
					<?=$affiliation['title'];?></a> 
					in <?=$affiliation['city'];?>, <?=$affiliation['state'];?>
				</h3>
				<p>
					<label>Homepage:</label> <input type="text" value="<?=$affiliation['url'];?>" class='large'>
				</p>
				<p>
					This group is administered by <a href="profile_user.php?ID=<?=$affiliation['contact_user_ID'];?>"><?=$affiliation['first_name']." ".$affiliation['last_name'];?></a>
				</p>				
				<form action="affiliations.php" method="POST">
					<input type=hidden name="action" value="remove">
					<input type=hidden name="affiliation_ID" value="<?=$affiliation['ID'];?>">
					<input type=submit value="Leave Group" class='submit'>
				</form>
			</li>
			<?php
		}
	}
	else
		print "<p>You are not yet affiliated with any groups.</p><br><br>";
	
	?>
</ul>

<?php
$result = mysql_query("SELECT * FROM Affiliations");
if(mysql_num_rows($result)>count($affiliations)){
?>
	<h2>Other Affiliations</h2>
	
	<form action="affiliations.php" method="POST">
		<input type="hidden" class="hidden" name="action" value="add">
		<select name="affiliation_ID">
			<?php
			while($row = mysql_fetch_assoc($result)){
				//Make sure person isn't already a member of this affiliation - Yes, there is a better way of doing this - Optimize later
				$result_temp = mysql_query("SELECT ID FROM Affiliations_Users WHERE Affiliations_Users.affiliation_ID = ".$row['ID']." AND Affiliations_Users.user_ID = ".$user_data['ID']." LIMIT 1");
				if(mysql_num_rows($result_temp)<=0){
					?>
					<option value="<?=$row['ID'];?>"><?=$row['title'];?> - <?=$row['city'];?>, <?=$row['state'];?></option>
					<?php
				}
			}
			?>
		</select>
		<input type="submit" class="submit" value="Become Affiliated">
	</form>
<?php
}
?>

<?php
include_once("includes/footer.php");
?>