<?php
/*
 *
 * @copyright (c) 2011 animegame.eu
 * @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public Licence
 *
 */

include_once (ROOT_PATH . '/include/defines.inc.php');
include_once (ROOT_PATH . '/include/clan.inc.php');
include_once (ROOT_PATH . '/include/messagefunctions.inc.php');
include_once (ROOT_PATH . '/include/attackenset.inc.php');
include_once (ROOT_PATH . '/include/arena.inc.php');
include_once (ROOT_PATH . '/include/kampf_wrapper.inc.php');
include_once (ROOT_PATH . '/include/semaphore.inc.php');
include_once (ROOT_PATH . '/include/event.inc.php');


defineIfNotDefined('MIN_MEMBERS', 5);
defineIfNotDefined('MAX_OPEN_REQUESTS', 3);
defineIfNotDefined('CLANFIGHTS_MAX_FIGHTS_PER_24H', 6);
defineIfNotDefined('DAVY_BACK_FIGHT', 1);
defineIfNotDefined('SURVIVAL', 2);
defineIfNotDefined('DURATION_DAVY_BACK_FIGHT', 15);
defineIfNotDefined('DURATION_SURVIVAL_FIGHT', 15);


defineIfNotDefined('ATTACK_SET_DAVY_BACK_FIGHT', 2);
defineIfNotDefined('ATTACK_SET_SURVIVAL', 2);

$GLOBALS['clan_challenge_buffered_instances'] = array ();


// Methods required within the request/accept phase

/**
 *
 * Challenge an other clan (Davy Back Fight)
 * @param array $user the user array
 * @param int $clanid the id of the clan to challenge
 * @param int $validTime the amount of hours that the challenge is valid
 */
function challengeClan(array $user, $clanid, $anzahl = 5, $type = DAVY_BACK_FIGHT, $validTime = 24) {
	$clan = getClan($user['clan']);
	$oclan = getClan($clanid);

	$ressource_clan1 = 'Clan:' . $user['clan'];
	$ressource_clan2 = 'Clan:' . $clanid;

	if(!$clan || !$oclan) {
		return 'Entweder bist du nicht in einem Clan oder der andere Clan existiert nicht mehr!!';
	}

	if($clan['leader'] != $user['id'] && $clan['co_leader'] != $user['id']){
		return 'Nur der Leader, bzw. der Co-Leader kann andere Clans herausfordern!!';
	}

	if($clan['id'] == $oclan['id']) {
		return 'Du kannst deinen eigenen Clan nicht herausfordern!!';
	}

	if(isClanLocked($user['clan']) || isClanLocked($clanid)) {
		// okay we cannot accept the challenge so make it inactive!
		mysql_query('UPDATE clan_challenge_requests SET active = FALSE WHERE clan_challenge_id = ' .$clan_challenge_id);
		return 'Einer der Clans erfüllt die Anforderungen an Clanfights nichtmehr (wahrscheinlich zu wenig Members)!';
	}



	if(!semaphoreUP($ressource_clan1)) {
		return 'Fehler beim Verarbeiten der Anfrage für  \'' . $clan['clanname'] . '\' versuche es bitte nochmal! ';
	}

	if(!semaphoreUP($ressource_clan2)) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		return 'Fehler beim Verarbeiten der Anfrage für  \'' . $oclan['clanname'] . '\' versuche es bitte nochmal! ';
	}

	// okay we have both semaphores :)

	$clan_challenges_my_clan = getOpenChallengeRequestCount($user['clan']);
	$clan_challenges_oth_clan = getOpenChallengeRequestCount($clanid);

	if($clan_challenges_my_clan > MAX_OPEN_REQUESTS) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Dein Clan hat schon die maximale Anzahl von Herausforderungen offen!';
	}

	if($clan_challenges_oth_clan > MAX_OPEN_REQUESTS) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Der Clan "'.$oclan['clanname'].'" hat schon die maximale Anzahl von Herausforderungen offen!';
	}

	// check if both clans have already been challengeing each other since 24h?
	$sql = 'SELECT count(*) as anzahl FROM clan_challenge_requests WHERE clan_requester IN ('.$user['clan'].', '.$clanid.') AND clan_challenged IN ('.$user['clan'].', '.$clanid.') AND  challenged_time > TIMESTAMPADD(day, -1, now())';
	$qry = mysql_query($sql);

	$row = mysql_fetch_assoc($qry);
	if($row['anzahl'] > 0) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Konnte den anderen Clan nicht herausfordern, da dieser Clan schoneinmal in den letzten 24 Stunden herausgefordert wurde!';
	}

	// it should not be possible to challenge a clan that already has an open match that is not yet calculated! ( not completely possible in sql)
	$sql = 'select count(k.anzahl) as anzahl from (SELECT count(*) as anzahl FROM clan_challenges c inner join clan_challenge_clans ccc on c.clan_challenge_id = ccc.clan_challenge_id where (calculated = 1 or enddate > now()) and clan_id IN ('.$user['clan'].', '.$clanid.') group by c.clan_challenge_id) k where k.anzahl = 0';
	//echo $sql .'<br>';
	$row = mysql_fetch_assoc(mysql_query($sql));
	if($row['anzahl'] > 0) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Du kannst einen Clan nicht herausfordern, wenn derzeit gerade ein Clanfight zwischen euch läuft oder offen ist!';
	}

	// now calculate how many open fights we currently had or have!
	$sql = 'select count(*) as anzahl from (SELECT count(*) as anz FROM clan_challenges c inner join clan_challenge_clans ccc on c.clan_challenge_id = ccc.clan_challenge_id where calculated = 0 or TIMESTAMPADD(day, -1, now()) < enddate and clan_id IN ('.$user['clan'].', '.$clanid.') group by clan_id) k where k.anz >= ' . CLANFIGHTS_MAX_FIGHTS_PER_24H;
	//echo $sql .'<br>';
	$row = mysql_fetch_assoc(mysql_query($sql));

	if($row['anzahl'] > 0) {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Einer der beiden Clans hat das Limit von ' . CLANFIGHTS_MAX_FIGHTS_PER_24H . ' offenen und abgeschlossenen Clanfights innerhalb von 24 erreicht. Daher kann die Herausforderung nicht versandt werden!';
	}


	// Fordere heraus!
	mysql_query('INSERT INTO clan_challenge_requests(clan_requester, clan_challenged, type, challenged_time, anzahl_chars, active) VALUES('.$user['clan'].', '.$clanid.','.$type.' , TIMESTAMPADD(HOUR, CURRENT_TIMESTAMP, 4), '.$anzahl.', true)');

	if(mysql_affected_rows() > 0) {
		if(is_numeric($oclan['leader'])) {
			sendMessage($user['nickname'], $oclan['leader'], 'Clan-Fight Herausforderung', 'Der Clan  '.$oclan['clanname'].' hat euch zu einem Clan-Fight herausgefordert! Über "Mein Clan" könnt ihr die Herausforderung annehmen!');
		}
		if(is_numeric($oclan['co_leader']) && $oclan['leader'] != $oclan['co_leader']) {
			sendMessage($user['nickname'], $oclan['co_leader'], 'Clan-Fight Herausforderung', 'Der Clan  '.$oclan['clanname'].' hat euch zu einem Clan-Fight herausgefordert! Über "Mein Clan" könnt ihr die Herausforderung annehmen!');
		}
	} else {
		semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
		semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
		return 'Konnte den anderen Clan nicht herausfordern!!';
	}

	semaphoreDown($ressource_clan1); // free the previously reserved semaphore!
	semaphoreDown($ressource_clan2); // free the previously reserved semaphore!
	return NULL;
}

/**
 * With this function the actual user accepts the challenge request from another clan!
 * @param int $challenged_clan the clan that has challenged us!
 * @param array $user
 */
function acceptChallengeRequest($challenged_clan, array $user) {
	$clan = getClan($user['clan']);

	if(!$clan) {
		return 'Du bist in keinem Clan!!';
	}

	if($clan['leader'] != $user['id'] && $clan['co_leader'] != $user['id']){
		return 'Nur der Leader, bzw. der Co-Leader kann herausforderungen anderer Clans annehmen!!';
	}

	$sql = 'SELECT * FROM clan_challenge_requests WHERE clan_challenged = ' .$user['clan'] . ' AND clan_requester = ' .$challenged_clan . ' AND active = TRUE AND challenged_time > TIMESTAMPADD(day, -1, now())';
	$clan_challenge = mysql_fetch_assoc(mysql_query($sql));

	if(!$clan_challenge) {
		return 'Konnte die Herausforderung nicht annehmen, da diese Herausforderung nicht exisitiert!';
	}

	if($user['clan'] != $clan_challenge['clan_challenged']) {
		return 'Du kannst die Herausforderung nicht annehmen, da du nicht im herausgeforderten Clan bist!';
	} else if ($clan_challenge['active'] != 1) {
		return 'Du kannst die Herausforderung nicht annehmen, da diese schon angenommen wurde!';
	}

	if(isClanLocked($clan_challenge['clan_challenged']) || isClanLocked($clan_challenge['clan_requester'])) {
		// okay we cannot accept the challenge so make it inactive!
		mysql_query('UPDATE clan_challenge_requests SET active = FALSE WHERE clan_challenge_id = ' .$clan_challenge_id);
		return 'Einer der Clans erfüllt die Anforderungen an Clanfights nichtmehr (wahrscheinlich zu wenig Members)!';
	}

	// now calculate how many open fights we currently had or have! // FIXME: Good idea to pach this in a semaphore?
	$sql = 'select count(*) as anzahl from (SELECT count(*) as anz FROM clan_challenges c inner join clan_challenge_clans ccc on c.clan_challenge_id = ccc.clan_challenge_id where calculated = 0 or TIMESTAMPADD(day, -1, now()) < enddate and clan_id IN ('.$clan_challenge['clan_challenged'].', '.$clan_challenge['clan_requester'].') group by clan_id) k where k.anz >= ' . CLANFIGHTS_MAX_FIGHTS_PER_24H;
//	echo $sql . '<br>';
	$row = mysql_fetch_assoc(mysql_query($sql));

	if($row['anzahl'] > 0) {
		return 'Einer der beiden Clans hat das Limit von ' . CLANFIGHTS_MAX_FIGHTS_PER_24H . ' offenen und abgeschlossenen Clanfights innerhalb von 24 erreicht. Daher kann die Herausforderung nicht angenommen werden!';
	}

	$oclan = getClan($clan_challenge['clan_requester']);

	mysql_query('UPDATE clan_challenge_requests SET active = false WHERE clan_challenged = ' .$user['clan'] . ' AND clan_requester = ' .$challenged_clan . ' AND active = TRUE AND challenged_time > TIMESTAMPADD(day, -1, now())');

	if(mysql_affected_rows() > 0) {
		// okay and for failsaveness just deactivate old requests
		mysql_query('UPDATE clan_challenge_requests SET active = false WHERE clan_challenged = ' .$user['clan'] . ' AND clan_requester = ' .$challenged_clan. ' AND active = TRUE');

		if(is_numeric($oclan['leader'])) {
			sendMessage($user['nickname'], $oclan['leader'], 'Clan-Fight', 'Der Clan  '.$oclan['clanname'].' hat eure Herausforderungen zu einem Clan-Fight angenommen! Über "Mein Clan" könnt ihr nun Chars anmelden!');
		}
		if(is_numeric($oclan['co_leader']) && $oclan['leader'] != $oclan['co_leader']) {
			sendMessage($user['nickname'], $oclan['co_leader'], 'Clan-Fight', 'Der Clan  '.$oclan['clanname'].' hat eure Herausforderungen zu einem Clan-Fight angenommen! Über "Mein Clan" könnt ihr nun Chars anmelden!');
		}

		$finished = FALSE;
		$id = -1;
		// get id
		while(!$finished) {
			$row = mysql_fetch_row(mysql_query('select IFNULL(max(clan_challenge_id),0) + 1 from clan_challenges'));
			mysql_query('INSERT INTO clan_challenges(clan_challenge_id, type, anzahl_chars) values('.$row[0].', '.$clan_challenge['type'].', '.$clan_challenge['anzahl_chars'].')');
			$finished = mysql_affected_rows() > 0;
			$id = $row[0];
		}

		// insert the participants :)
		mysql_query('INSERT INTO clan_challenge_clans(clan_challenge_id, clan_id, elo) values('.$id.', '.$clan['id'].', '.$clan['elo'].')');
		mysql_query('INSERT INTO clan_challenge_clans(clan_challenge_id, clan_id, elo) values('.$id.', '.$oclan['id'].', '.$clan['elo'].')');

		// we have everything we need for this challenge to be opened :)

	} else {
		return 'Du kannst die Herausforderungen nicht annehmen. Wurde die Herausforderung schon angenommen?';
	}

	return NULL;
}

/**
 * With this function the actual user from the challenged clan denies the challenge request!
 * @param int $challenged_clan
 * @param array $user
 */
function denyChallengeRequest($challenged_clan, array $user) {
	$clan = getClan($user['clan']);

	if(!$clan) {
		return 'Du bist in keinem Clan!!';
	}

	if($clan['leader'] != $user['id'] && $clan['co_leader'] != $user['id']){
		return 'Nur der Leader, bzw. der Co-Leader kann Herausforderungen anderer Clans ablehnen!!';
	}

	$clan_challenge = mysql_fetch_assoc(mysql_query('SELECT * FROM clan_challenge_requests WHERE clan_challenged = ' .$user['clan'] . ' AND clan_requester = ' .$challenged_clan . ' AND active = TRUE AND challenged_time > TIMESTAMPADD(day, -1, now())'));

	if(!$clan_challenge) {
		return 'Konnte die Herausforderung nicht annehmen, da diese Herausforderung nicht exisitiert!';
	}

	if($user['clan'] != $clan_challenge['clan_challenged']) {
		return 'Du kannst die Herausforderung nicht ablehnen, da du nicht im herausgeforderten Clan bist!';
	} else if ($clan_challenge['active'] != 1) {
		return 'Du kannst die Herausforderung nicht ablehnen, da diese schon angenommen wurde!';
	}

	// okay seems to be okay
	mysql_query('UPDATE clan_challenge_requests SET active = false WHERE clan_challenged = ' .$user['clan'] . ' AND clan_requester = ' .$challenged_clan. ' AND active = TRUE');
	return NULL;
}

/**
 * Reads out the given date from the table "clan_challenge"
 * @param int $challenge_id
 * @param bool $buffer
 */
function getChallenge($challenge_id, $buffer = TRUE) {
	if($buffer && isset($GLOBALS['clan_challenge_buffered_instances'][$challenge_id])) {
		return $GLOBALS['clan_challenge_buffered_instances'][$challenge_id]; // okay, we already buffered the clan :)
	}

	$qry = mysql_query('SELECT * from clan_challenges WHERE clan_challenge_id = ' .$challenge_id);
	$GLOBALS['clan_challenge_buffered_instances'][$challenge_id] = mysql_fetch_assoc($qry);
	return $GLOBALS['clan_challenge_buffered_instances'][$challenge_id]; // okay, we already buffered the clan :)
	}

function getOpenChallengeRequests($clanid) {
	$array = array();
	if(isClanLocked($clanid)) {
		return $array;
	}

	$sql = 'SELECT * from clan_challenge_requests WHERE challenged_time > TIMESTAMPADD(day, -1, now()) and active = TRUE AND (clan_requester = '.$clanid.' OR clan_challenged = '.$clanid.')';
//	echo $sql . '<br>';
	$qry = mysql_query($sql);
	while($row = mysql_fetch_assoc($qry)) {
		$array[] = $row;
	}
	return $array;
}

function getOpenChallengeRequestCount($clanid) {
	if(isClanLocked($clanid)) {
		return 0;
	}
	$sql = 'SELECT count(*) from clan_challenge_requests where challenged_time > TIMESTAMPADD(day, -1, now()) and active = TRUE AND (clan_requester = '.$clanid.' OR clan_challenged = '.$clanid.')';
//	echo $sql . '<br>';
	$row = mysql_fetch_row(mysql_query($sql));
	return $row[0];
}

// this method returns the challenge ids for open fights
function getOpenChallengeIDs($clanid) {
	// before doing anything check if we are locked
	$array = array();
	if(isClanLocked($clanid)) {
		return $array;
	}

	$sql = 'SELECT cc.clan_challenge_id FROM clan_challenges AS cc inner join clan_challenge_clans AS ccp ON cc.clan_challenge_id = ccp.clan_challenge_id WHERE clan_id = ' . $clanid . ' AND calculated = FALSE';
	$qry = mysql_query($sql);
	while($row = mysql_fetch_row($qry)) {
		$array[] = $row[0];
	}
	// return the ids
	return $array;
}

function getParticipatingClanIDs($clan_challenge_id) {
	$array = array();
	$sql = 'SELECT clan_id FROM clan_challenge_clans AS ccp WHERE clan_challenge_id = ' . $clan_challenge_id;
	$qry = mysql_query($sql);
	while($row = mysql_fetch_row($qry)) {
		$array[] = $row[0];
	}
	// return the ids
	return $array;
}

function isCharBusyWithClanfighting($char_id) {
	$sql = 'SELECT count(*) as anzahl FROM clan_challenge_participants ccp INNER JOIN clan_challenges cc on ccp.clan_challenge_id = cc.clan_challenge_id WHERE cc.calculated = FALSE AND char_id = ' .$char_id;
	$row = mysql_fetch_row(mysql_query($sql));
	return $row[0] > 0;
}

function getParticipatingCharIDs($clan_challenge_id, $clan_id) {
	$array = array();
	$sql = 'SELECT char_id, slot FROM clan_challenge_participants WHERE clan_challenge_id = ' . $clan_challenge_id . ' AND clan_id = ' .$clan_id;
	$qry = mysql_query($sql);
	while($row = mysql_fetch_assoc($qry)) {
		$array[$row['slot']] = $row['char_id'];
	}
	// return the ids
	return $array;
}

// returns the last challenge ids (beginning with the latest to the first)
function getHistoricalChallengeIDs($clanid, $limit = NULL) {
	$addition = '';
	if($limit !== null && is_numeric($limit)) {
		$addition = ' LIMIT ' .$limit;
	}
	$sql = 'SELECT cc.clan_challenge_id FROM clan_challenges AS cc inner join clan_challenge_clans AS ccp ON cc.clan_challenge_id = ccp.clan_challenge_id WHERE clan_id = ' . $clanid . ' AND calculated = TRUE ORDER BY cc.date DESC ' . $addition;
	$qry = mysql_query($sql);
	while($row = mysql_fetch_row($qry)) {
		$array[] = $row[0];
	}
	// return the ids
	return $array;
}

// Checks if the clan is locked, will lock it if required!
function isClanLocked($clanid) {
	if(!is_numeric($clanid)) {
		return true;
	}
	// we really want to know if we are locked at the moment. So readout everything at once ;), right join so we always have a row :D
	$sql = 'SELECT *, locked_until < now() as `lock`, (Select count(id) from user where clan = c2.id) as members FROM clan_locked right join clan c2 on c2.id = clan_locked.clanid where c2.id = ' . $clanid;
//	echo $sql.'<br>';
	$lock = mysql_fetch_assoc(mysql_query($sql));

	if($lock['lock'] == 0) { // don't matter if it is 0 or NULL

		// we do not have data in the clan locked table so we are not locked :D
		// or
		// we do have data but it seems we are not locked anymore ;)

		// are we still having enough members??
		if($lock['members'] >= MIN_MEMBERS && $lock['lock'] === NULL) {
			// key so every thing seems to be fine :)
			return false; // the only case we may return false!
		} else if($lock['lock'] === NULL){ // we need to insert a row
			// INSERT
			$sql = 'INSERT INTO clan_locked(clanid, locked_until) values('.$clanid.', TIMESTAMPADD(HOUR, 24, CURRENT_TIMESTAMP))';
//			echo $sql.'<br>';
			mysql_query($sql);
		} else if($lock['members'] < MIN_MEMBERS){ // we have to update the actual row
			// UPDATE
			$sql = 'UPDATE clan_locked set locked_until = TIMESTAMPADD(HOUR, 24, CURRENT_TIMESTAMP) WHERE clanid = ' .$clanid;
//			echo $sql.'<br>';
			mysql_query($sql);
		}
	}

	return true;
}


/**
 * This function lets a user take part in the clan fight! The clan fight will be calculated if all chars have been registered.
 * A challenge can only be joined if there is no other char of the same user joined. If the given slot is free and the challangeid is valid.
 * @param int $clan_challenge_id the id of the challenge
 * @param array $user the user array
 * @param int $charid the id of the char that should join
 */
function joinChallenge($clan_challenge_id, array $user, $charid, $slot ) {
	$clan = getClan($user['clan']);
	$char = getChar($charid);

	if(!$clan) {
		return 'Du bist in keinem Clan!!';
	}

	if($char['besitzer'] != $user['id']) {
		return 'Du kannst den Char nicht an dem Kampf teilnehmen lassen, da er dir nicht gehört!';
	}

	if($char['status'] != 'Frei') {
		return 'Du kannst den Char nicht an dem Kampf teilnehmen lassen, da er nicht frei ist!';
	}

	$clan_challenge = getChallenge($clan_challenge_id);

	if($slot < 1 && $slot > $clan_challenge['anzahl_chars']) {
		return 'Der Slot ' . $slot . ' ist f&uuml;r diesen Kampf nicht verf&uuml;gbar!!';
	}

	$clan_ids = getParticipatingClanIDs($clan_challenge['clan_challenge_id']);

	if(array_search($user['clan'], $clan_ids) === FALSE) {
		// the clan does not match a participant!!
		return 'Du bist in keinem Clan der an dieser Challenge teilnimmt!';
	}

	// block the user actions so we can ensure he won't register multiple of its chars here!
	$resource = 'User:'.$user['id'];
	if(!semaphoreUP($ressource)) {
		return 'Du kannst den Char nicht an dem Kampf teilnehmen lassen, da du scheinbar gerade auch mit was anderem beschäftigt bist, versuche es bitte nochmal!';
	}

	foreach ($clan_ids as $clan_id) {
		if(isClanLocked($clan_id)) {
			mysql_query('DELETE FROM clan_challenges WHERE clan_challenge_id = '.$clan_challenge_id);
			semaphoreDown($ressource);
			return 'Einer der Clans erfüllt die Anforderungen an Clanfights nichtmehr (wahrscheinlich zu wenig Members)!';
		}
	}

	// okay does this user already has a char in the fight??
	$qry = mysql_query('SELECT count(*) as anzahl FROM clan_challenge_participants ccp inner join chars c on ccp.char_id = c.id WHERE besitzer = ' .$user['id']);
	$row = mysql_fetch_assoc($qry);

	if($row['anzahl'] != 0) {
		semaphoreDown($ressource);
		return 'Konnte den Char nicht hinzufügen. Da du schon einen Char angemeldet hast!';
	}

	mysql_query('INSERT INTO clan_challenge_participants(clan_challenge_id, clan_id, char_id, slot) values('.$clan_challenge_id.', '.$user['clan'].', '.$charid.', '.$slot.')');
	if(mysql_affected_rows() == 0) {
		semaphoreDown($ressource);
		return 'Konnte den Char nicht hinzufügen. Slot mittlerweile schon belegt?';
	}

	// okay, now try to update the challenge to close the challenge and to start the calculating (as long we can do it ;))
	$sql = 'update clan_challenges AS cc SET calculated = TRUE WHERE '.
				'(SELECT count(*) FROM clan_challenge_participants AS ccp ' .
					'WHERE ccp.clan_challenge_id = cc.clan_challenge_id AND clan_id = '.$clan_ids[0].
				') = ' . $clan_challenge['anzahl_chars'] .
				' AND ' .
				'(SELECT count(*) FROM clan_challenge_participants AS ccp ' .
					'WHERE ccp.clan_challenge_id = cc.clan_challenge_id AND clan_id = '.$clan_ids[1].
				') = ' . $clan_challenge['anzahl_chars'];

	mysql_query($sql);
	$rows = mysql_affected_rows();
	semaphoreDown($ressource);

	if($rows  > 0) {
		// okay we now have a complete competition and the challenge is closed :)
		calculateChallenge($clan_challenge_id);
	}

}

/**
 *
 * Lets the user to remove his char from the challenge
 * @param integer $clan_challenge_id
 * @param array $user
 * @param integer $charid
 */
function leaveChallenge($clan_challenge_id, array $user, $charid) {
	$clan = getClan($user['clan']);
	$char = getChar($charid);

	if(!$clan) {
		return 'Du bist in keinem Clan!!';
	}

	if($char['besitzer'] != $user['id']) {
		return 'Du kannst den Char nicht vom Kampf zurückziehen, da er dir nicht gehört!';
	}

	// Okay, the rest we can check with the delete statement much easier!
	// basically the check consists of a) is the challenge not yet calculated b) is char active in the challenge?
	$sql = 'DELETE FROM clan_challenge_participants WHERE (SELECT calculated FROM clan_challenges AS cc WHERE cc.clan_challenge_id = clan_challenge_participants.clan_challenge_id) = FALSE AND char_id = ' . $charid;
	mysql_query($sql);

	if(mysql_affected_rows() == 0) {
		return 'Der Char kann nicht aus dem Kampf zurückgezogen werden.';
	}

	return NULL;
}

/**
 * This function does the calculation of the clan fight.
 * @param int $clan_challenge_id the id of the challenge
 */
function calculateChallenge($clan_challenge_id) {
	$challenge = getChallenge($clan_challenge_id);

	$start_time = time();

	// okay the calculated flag is already set so readout all the required data for further processing!
	$clan_ids = getParticipatingClanIDs($clan_challenge_id);
	$clan_chars = array();

	$event_id = createEvent(EVENT_CLAN_FIGHT);

	foreach ($clan_ids as $clan_id) {
		$clan_char_ids = getParticipatingCharIDs($clan_challenge_id, $clan_id);
		foreach ($clan_char_ids as $slot => $char_id) {
			addParticipant($event_id, getChar($char_id));
			$clan_chars[$clan_id][$slot] = getChar($char_id);
		}
	}

	$result = NULL;

	// okay now determine the type of fight
	switch($challenge['type']) {
		case DAVY_BACK_FIGHT:
			$result = calculateDavyBackClanFight($event_id, $clan_ids, $clan_chars, $start_time);
			if(!is_numeric($result))
				return $result;
			break;
		case SURVIVAL:
			return calculateSurvivalClanFight($event_id, $clan_ids, $clan_chars, $start_time);
			if(!is_numeric($result))
				return $result;
			break;
		default:
			// cannot create anything -.-
			return 'Der Clanfight Typ "'.$challenge['type'].'" wird nicht unterstützt, bitte melde dich beim Administrator!' ;
	}

	mysql_query('UPDATE clan_challenges set event_id = '.$event_id.', enddate = \''.date("Y-m-d H:i:s",$result).'\' WHERE clan_challenge_id = ' .$clan_challenge_id);

	return NULL;
}

function calculateDavyBackClanFight($event_id, array $clan_ids, array $clan_char_array, $start_time) {
	$duration = DURATION_DAVY_BACK_FIGHT * 60;
	// okay, davy back fights are 1 vs. 1 and the winner is the one that has won the most fights.
	if(count($clan_char_array) != 2) {
		return 'Davy Back Fights können nur zwischen 2 Clans ausgetragen werden und nicht von ' . count($clan_char_array);
	}
	if(count($clan_char_array[$clan_ids[0]]) != count($clan_char_array[$clan_ids[1]])) {
		return 'Davy Back Fights können nur zwischen Clans mit der selben Anzahl von Chars ausgetragen werden!';
	}
	$count_chars = count($clan_char_array[$clan_ids[0]]);
	// okay ... now do the calculation!
	for($runde = 1; $runde<=$count_chars;$runde++) {
		$char_clan_1 = $clan_char_array[$clan_ids[0]][$runde];
		$char_clan_2 = $clan_char_array[$clan_ids[1]][$runde];

		// we do not need to know right now who won the battle! This is required in the post processing (cronjob)!
		battle($event_id, $char_clan_1, $char_clan_2, ATTACK_SET_DAVY_BACK_FIGHT, $start_time + ($runde-1) * $duration, $start_time + $runde * $duration);
	}
	return $start_time + ($runde-1) * $duration;
}

function calculateSurvivalClanFight($event_id, array $clan_ids, array $clan_char_array, $start_time) {
	$duration = DURATION_SURVIVAL_FIGHT * 60;
	// okay, survival fights are 1 vs. 1 and the winner is the one that has the last man standing.
	if(count($clan_char_array) != 2) {
		return 'Survival Fights können nur zwischen 2 Clans ausgetragen werden und nicht von ' . count($clan_char_array);
	}
	if(count($clan_char_array[$clan_ids[0]]) != count($clan_char_array[$clan_ids[1]])) {
		return 'Survival Fights können nur zwischen Clans mit der selben Anzahl von Chars ausgetragen werden!';
	}
	$count_chars = count($clan_char_array[$clan_ids[0]]);

	$counter_clan_1 = 1;
	$counter_clan_2 = 1;
	$char_clan_1 = $clan_char_array[$clan_ids[0]][$counter_clan_1];
	$char_clan_2 = $clan_char_array[$clan_ids[1]][$counter_clan_2];

	$runde = 0;
	// As long as char 1 and char 2 are set
	while($char_clan_1 != NULL && $char_clan_2 != NULL) {
		$runde++;
		$sieger = battle($event_id, $char_clan_1, $char_clan_2, ATTACK_SET_SURVIVAL, $start_time + ($runde-1) * $duration, $start_time + $runde * $duration);
		if($sieger['id'] != $char_clan_1['id']) {
			// the loser is of clan 1
			$char_clan_1 = $clan_char_array[$clan_ids[0]][++$counter_clan_1];
			$char_clan_2 = $sieger; // the new array contains the adjusted health parameter
		} else {
			// the loser is of clan 2
			$char_clan_2 = $clan_char_array[$clan_ids[1]][++$counter_clan_2];
			$char_clan_1 = $sieger; // the new array contains the adjusted health parameter
		}
	return $start_time + $runde * $duration;
	}

}

/**
 * This function calculates the battle between two chars.
 * @param int $event_id the event id
 * @param array $char1
 * @param array $char2
 * @param int $attack_set the attack set that should be used!
 * @return the winners array
 */
function battle($event_id, array $char1, array $char2, $attack_set, $startTimestamp, $endTimestamp) {
	$char1['attacken'] = implode(',', getCharAttackSet($char1['id'], $attack_set));
	$char2['attacken'] = implode(',', getCharAttackSet($char2['id'], $attack_set));

	$combinedArray = calculateFight($char1, $char2);

	$exp = calculateExperience($char1, $char2, $combinedArray['winner'], 0.01); // very few exp

	$combinedArray['data'][KEY_EXP_CHAR1] = $exp[$char1['id']];
	$combinedArray['data'][KEY_EXP_CHAR2] = $exp[$char2['id']];

	$arena = calculateArenaData(null, $char1, $char2, 0.01);

	$combinedArray['data'][KEY_LOGE] = $arena['loge'];
	$combinedArray['data'][KEY_SITZ] = $arena['sitz'];
	$combinedArray['data'][KEY_STEH] = $arena['steh'];

	if($combinedArray['winner'] == $char1['id']) {
		$combinedArray['data'][KEY_GELD_CHAR1] = $arena['geld'] * 0.7;
		$combinedArray['data'][KEY_GELD_CHAR2] = $arena['geld'] * 0.3;
	} else {
		$combinedArray['data'][KEY_GELD_CHAR2] = $arena['geld'] * 0.7;
		$combinedArray['data'][KEY_GELD_CHAR1] = $arena['geld'] * 0.3;
	}

	// first persist the fight and then check who was the winner and adjust the char array for him ;)
	persistFight($event_id, $combinedArray, $startTimestamp, $endTimestamp);
	return;

	// now get the winners array
	$rounds = $combinedArray['rounds'];
	$lastRound = $rounds[count($rounds) - 1];

	$newChar = null;
	if($lastRound['char1_array']['id'] == $combinedArray['winner']){
		$newChar = $lastRound['char1_array'];
	} else {
		$newChar = $lastRound['char2_array'];
	}
	$newChar['mp'] = $newChar['mp']. ','.$newChar['mp_max'];
	$newChar['hp'] = $newChar['hp']. ','.$newChar['hp_max'];
	return $newChar;
}


function getClanFightCapableClanIds() {
	$clan_info = getAllClans();
	$ids = array();
	foreach ($clan_info as $clan) {
		if(!isClanLocked($clan['id'])) {
			$ids[] = $clan['id'];
		}
	}
	return $ids;
}

/**
 * Checks if the user is authorized to coordinate clanfights (if a id is given, it checks this for a given clan_fight)
 *
 * @param int $clan_id the clan that is in scope
 * @param int $user_id the user that is in scope
 * @param int $clan_fight_id the optional clan_fights that is in scope
 */
function isAuthorizedClanfightCoordinator($clan_id, $user_id, $clan_fight_id = NULL) {
	return true;
}

?>