<?php
// TODO: Letzte Aktivität
$categories = array(
	'Information' => array('Info', '#FFFFFF'),
	'Noobfehler' => array('Noob', '#008000'),
	'Hintergrund' => array('Hintergrund', '#008000'),
	'OOC-Sprache' => array('OOC-Sprache', '#008000'),
	'NON-RP' => array('NON-RP', '#00FF00'),
	'Charakterauslegung' => array('Charausleg', '#FFFF00'),
	'Powergaming' => array('PGaming', '#710071'),
	'Poweremotes' => array('PEmote', '#FFFF00'),
	'NON-RP+' => array('NON-RP+', '#800000'),
	'OOC-Using' => array('OOC-Using', '#AA1111'),
	'Bugusing' => array('Bugusing', '#800000'),
	'Beleidigung' => array('Beleidigung', '#FF0000'),
	'SEX_GEWALT' => array('S&G', '#FF6600'),
	'Multiaccounts' => array('X-Accs', '#FF0000'),
	'Charstory' => array('Charstory', '#FF6F6F'),
	'Sonstiges' => array('Sonst', 'black')
);

require_once( './core.php' );

if( !isset( $user ) || !$user->can_access( 'accounts_admin' ) ) access_error();

function get_time_modification($age) {
	// die ersten 90 Tage zählt jede Strafe voll; danach linear degressiv. Nach 540 Tagen zählen Strafen nicht mehr zum Index
	$age = floor($age / 86400)	;

	$y = -1/450 * $age + 1.2;  // Geradengleichung y=m * x + c
	$y = max (0, min(1, $y)); // Jenseits von 540 Tagen hat die Funktion den Wert 0
	
	return ($y);
}

if($_REQUEST['action'] == "unassign") {
	// TODO: IG-Logging
	// TODO: Inform GMs: "Zuweisung des Rufs/der Beschwerde von Lennart (Mr. Spock) zurückgenommen von 'Aurax' (HP)."
	$MySQL->query("UPDATE server.calls SET responsible = NULL WHERE status = 1 AND call_id = '".intval($_REQUEST['call_id'])."'");
	unset($_REQUEST['action']);
}
if($_REQUEST['action'] == "assign") {
	// TODO: IG-Logging
	// TODO: Inform GMs: "Ruf/Beschwerde von Lennart (Mr. Spock) übernommen von 'Aurax' (HP)."
	$MySQL->query("UPDATE server.calls SET responsible = '".$user->ID."' WHERE status = 1 AND call_id = '".intval($_REQUEST['call_id'])."'");
	unset($_REQUEST['action']);
}
if($_REQUEST['action'] == "delete") {
	// TODO: IG-Logging
	// TODO: Inform Player. "Dein GM-Ruf von 12:45:30 wurde gelöscht, als du nicht eingeloggt warst."
	// TODO: Inform GMs: "Ruf/Beschwerde von Lennart (Mr. Spock) wurde von 'Aurax' über die HP gelöscht."
	$MySQL->query("UPDATE server.calls SET responsible = '".$user->ID."', status = 0 WHERE status = 1 AND call_id = '".intval($_REQUEST['call_id'])."'");
	unset($_REQUEST['action']);
}
if($_REQUEST['action'] == "say") {
	$calls = (array)$MySQL->query_first("SELECT TIMEDIFF(NOW(), call_time) as age, UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(call_time) as call_secs, call_id, charid, charid_accusator, call_type, status, responsible, message FROM server.calls WHERE status = 1 ORDER BY call_time DESC");
	$calls = array_merge($calls, (array)$MySQL->query_first("SELECT server.chars.name as char_name, server.chars.online as online, web.accounts.name as account_name, web.accounts.accountid as accountid FROM (server.chars LEFT JOIN web.accounts ON server.chars.accountid = web.accounts.accountid) WHERE charid = ".intval($calls['charid'])));
	$calls = array_merge($calls,(array)$MySQL->query_first("SELECT online as account_online FROM server.chars WHERE accountid = '".intval($calls['accountid'])."' LIMIT 0,1"));
	$calls = array_merge($calls,(array)$MySQL->query_first("SELECT name as responsible_account_name FROM web.accounts WHERE accountid = ".intval($calls['responsible'])));
	$calls = array_merge($calls,(array)$MySQL->query_first("SELECT online as responsible_account_online FROM server.chars WHERE accountid = '".intval($calls['responsible'])."' LIMIT 0,1"));			
	if($result_prepare['call_type']=='B') {
		$calls = array_merge($calls,(array)$MySQL->query_first("SELECT server.chars.name as char_name_accusator, server.chars.online as online_accusator, web.accounts.name as account_name_accusator, web.accounts.accountid as accountid_accusator FROM (server.chars LEFT JOIN web.accounts ON server.chars.accountid = web.accounts.accountid) WHERE charid = ".intval($calls['charid_accusator'])));
		$calls = array_merge($calls,(array)$MySQL->query_first("SELECT online as accusator_account_online FROM server.chars WHERE accountid = '".intval($calls['accountid_accusator'])."' LIMIT 0,1"));
	}
	$Smarty->assign('calls', $calls);
	$page['content'] = $Smarty->fetch( 'jail_send_message.tpl' );
}
if($_REQUEST['action'] == "commit_say") {
	if($_REQUEST['who'] == 'R') {
		$charid = $MySQL->query_first("SELECT charid_accusator FROM server.calls WHERE call_id = '".intval($_REQUEST['call_id'])."'");
	}
	else {
		$charid = $MySQL->query_first("SELECT charid FROM server.calls WHERE call_id = '".intval($_REQUEST['call_id'])."'");
	}
	$result = $MySQL->query_first("SELECT serial, accountid, online FROM server.chars WHERE charid = '".$charid['charid']."'");
	if ($result['online']==0 AND $_REQUEST['send_offline']==1) {
		// Char offline
		//TODO: IG-Logging
		$MySQL->query("INSERT INTO messages SET sender = '".$user->ID."', receiver = '".intval($result['accountid'])."', time = '".time()."', 	subject = 'Offline-Zustellung einer GM-Nachricht', message = '".$_REQUEST['message']."'");
		$MySQL->query("UPDATE server.calls SET responsible = '".$user->ID."' WHERE status = 1 AND call_id = '".intval($_REQUEST['call_id'])."'");
	}
	elseif($result['online']==1) {
		// TODO: IG-Message
		echo "Message dropped";		
	}
	unset($_REQUEST['action']);	
}
if($_REQUEST['action'] == "commit_punish") {
	$case = $MySQL->query_first("SELECT accountid FROM server.cases WHERE case_id = '".intval($_REQUEST['case_id'])."'");
	if ($case['accountid'] > 0) {
		$MySQL->query("START TRANSACTION");
	
		if($_REQUEST['player_information'] == 'Offline') {
			$MySQL->query("INSERT INTO messages SET sender = '".$user->ID."', receiver = '".intval($case['accountid'])."', time = '".time()."', subject = 'Offline-Zustellung einer Strafe', message = '".$_REQUEST['message']."'");
		}
	
		$MySQL->query("INSERT INTO server.court_decisions SET case_id = '".intval($_REQUEST['case_id'])."', accountid = '".$case['accountid']."', decision_type = '".$_REQUEST['decision_type']."', sentence_param = '".intval($_REQUEST['sentence_param'])."', player_information = '".$_REQUEST['player_information']."', sentenced_by = '".$user->ID."', sentence_date = NOW(), decision_status = 1, message = '".$_REQUEST['message']."'");
		$MySQL->query("UPDATE server.cases SET responsible = '".$user->ID."', lastchanged = NOW() WHERE case_id = '".intval($_REQUEST['case_id'])."'");
	
		$MySQL->query("COMMIT");
	}
	
	$_REQUEST['action']="account_details";
	$_REQUEST['accountid'] = $case['accountid'];
}
if($_REQUEST['action'] == "punish") {
	list ($name )= $MySQL->query_first("SELECT web.accounts.name FROM server.cases LEFT JOIN web.accounts ON server.cases.accountid = web.accounts.accountid WHERE server.cases.case_id = '".intval($_REQUEST['case_id'])."'");
	
	$Smarty->assign('page_title', "Wachraum &raquo; Strafe aussprechen &raquo; ".$name);
	$Smarty->assign('page_title_long', "Wachraum &raquo; Strafe aussprechen &raquo; ".$name);
	$Smarty->assign('page_title_site', "Strafe aussprechen '".$name."'");
	
	$Smarty->assign('case_id', $_REQUEST['case_id']);
	$page['content'] = $Smarty->fetch( 'jail_punish.tpl' );
}
if($_REQUEST['action'] == "bla") {

	unset($_REQUEST['action']);
}
if($_REQUEST['action'] == "account_details") {
	$accountid = intval($_REQUEST['accountid']);
	
	// fetch charhistory
	$char_history = $MySQL->fetch_complete("SELECT name, accesslevel, volk, geschlecht, level, aktiviert, aktiviert_von, aktivierungszeitpunkt, lastchanged FROM server.chars WHERE accountid = '".$accountid."' ORDER BY aktiviert,charid");
	// TODO: Löschdetails
	$Smarty->assign('char_history', $char_history);
	
	// fetch account details
	$account_details = $MySQL->query_first("SELECT accountid, name, email, icq, FROM_UNIXTIME(register_time) as register_time, FROM_UNIXTIME(last_activity) as last_activity, max_characters, max_staffcharacters, gs_AccessLevel FROM accounts WHERE accountid = '".$accountid."'");
	$Smarty->assign('account_details', $account_details);
	$Smarty->assign('page_title', "Wachraum &raquo; Aktenschrank &raquo; ".$account_details['name']);
	$Smarty->assign('page_title_long', "Wachraum &raquo; Aktenschrank &raquo; ".$account_details['name']);
	$Smarty->assign('page_title_site', "Akte '".$account_details['name']."'");
	
	// fetch punishment details
	$punishment_details = $MySQL->fetch_complete("SELECT case_id, decision_type, sentence_param, sentenced_by, sentence_date, UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(sentence_date) as age, UNIX_TIMESTAMP(sentence_date) as sentence_date_secs FROM server.court_decisions WHERE accountid = '".$accountid."' ORDER BY sentence_date");

	// fetch cases
	$cases_prepare = $MySQL->fetch_complete("SELECT * FROM server.cases WHERE accountid = '".$accountid."'");
	$cases = array();
	foreach($cases_prepare as $item) {
		$prepare = (array)$item;
		list ($prepare['char_name']) = $MySQL->query_first("SELECT name FROM server.char_creation WHERE charid = '".$item['charid']."' AND accountid = '".$accountid."'");
		list($prepare['filed_by_name']) = $MySQL->query_first("SELECT name FROM accounts WHERE accountid = '".$prepare['filed_by']."'");
		list ($prepare['responsible_name']) = $MySQL->query_first("SELECT name FROM accounts WHERE accountid = '".$prepare['responsible']."'");
		$categories_prepare = explode(',', $prepare['categories']);
		$prepare['categories'] = "";
		foreach ($categories_prepare as $citem) {
			$prepare['categories'] .= "<font color=\"".$categories[$citem][1]."\"><b>".$categories[$citem][0]."</b></font> ";	
		}
		$prepare['categories'] .= " / <i>".$item['jail_behaviour']."</i>";
		$prepare['punishment'] = $MySQL->query_first("SELECT server.court_decisions.*, web.accounts.name as sentenced_by_name FROM server.court_decisions LEFT JOIN web.accounts ON server.court_decisions.sentenced_by = web.accounts.accountid WHERE server.court_decisions.case_id = '".$item['case_id']."' AND server.court_decisions.decision_status = 1 LIMIT 1");
		list ($prepare['comments_count']) = $MySQL->query_first("SELECT COUNT(*) FROM server.case_comments WHERE case_id = '".$item['case_id']."'");
		$prepare['last_comment'] = $MySQL->query_first("SELECT server.case_comments.last_edited, web.accounts.name as last_edited_by FROM server.case_comments LEFT JOIN web.accounts ON server.case_comments.last_edited_by = web.accounts.accountid WHERE case_id = '".$item['case_id']."' ORDER BY last_edited DESC LIMIT 0,1");
		$cases[] = $prepare;
	}
	
	$Smarty->assign('cases', $cases);
	
	// calculate court_index und punkte
	//'Ermahnung' (0.5),'Verwarnung' (1*Param[Punkte]),'Jail' (3*Param[Tage]),'Punkte_Jail' (20),'Foren-Verwarnung (3*Param[Stufe])','Block (5*Param[Tage])','Begnadigung' (-1*Param)
	$stats['court_index'] = 0;
	$stats['ermahnungen'] = 0;
	$stats['punkte'] = 0;
	$stats['verwarnungen'] = 0;
	$stats['jail_tage'] = 0;
	$stats['jail_aufenthalte'] = 0;
	$stats['foren_verwarnungen'] = 0;
	$stats['punkte_ueberschreitungen'] = 0;
	
	foreach($punishment_details as $item) {
		switch($item['decision_type']) {
			case "Ermahnung":
				$stats['court_index'] += 0.5 * get_time_modification($item['age']);
				$stats['ermahnungen']++;
			break;
			case "Verwarnung":
				$stats['court_index'] += 1 * $item['sentence_param'] * get_time_modification($item['age']);
				$stats['verwarnungen']++;
				$stats['punkte_sum'] += $item['sentence_param'];
				if(isset($letzte_punktevergabe) === true) {
					$months_passed = floor((max(0, $item['sentence_date_secs'] - $letzte_punktevergabe)) / 2592000); // 60*60*24* 30[Tage]
					$stats['punkte'] = max(0, $stats['punkte']-8*$months_passed) + $item['sentence_param'];  // 8 Punkte werden im Monat abgebaut
				}
				else $stats['punkte'] = $item['sentence_param'];
				$letzte_punktevergabe = $item['sentence_date_secs'];
			break;
			case "Jail":
				$stats['court_index'] += 3 * $item['sentence_param'] * get_time_modification($item['age']);
				$stats['jail_aufenthalte']++;
				$stats['jail_tage'] += $item['sentence_param'];
			break;
			case "Punkte_Jail":
				$stats['court_index'] += 20 * get_time_modification($item['age']);
				$stats['punkte_ueberschreitungen']++;
				$stats['punkte'] = max(0, min($stats['punkte']-10,18));  // 10 Punkte werden bei Jail-Aufenthalt wegen Punkteüberschreitung abgezogen; wenn immer noch über 18 Punkte, dann runter auf 18
			break;
			case "Foren-Verwarnung":
				$stats['court_index'] += 3 * $item['sentence_param'] * get_time_modification($item['age']);
				$stats['foren_verwarnungen']++;
			break;
			case "Block":
				$stats['court_index'] += 5 * $item['sentence_param'] * get_time_modification($item['age']);
			break;
			case "Begnadigung":
				$stats['court_index'] =  max(0, $stats['court_index']-$item['sentence_param'] * get_time_modification($item['age']));
			break;
		}
			
	} 
	$months_passed = floor((max(0, time()-$letzte_punktevergabe)) / 2592000); // 60*60*24* 30[Tage]
	$stats['punkte'] = max(0, $stats['punkte']-8*$months_passed);  // Abbauen der Punkte seit letzter Punktvergabe
	$stats['court_index'] = round($stats['court_index'], 2);
	$Smarty->assign('stats', $stats);
	
	// TODO: Punkte aktualisieren in accounts	
	$page['content'] = $Smarty->fetch( 'jail_file.tpl' );
}
if(isset($_REQUEST['action']) === false) { // default
	// letztes Betreten der Jail-Übersicht speichern
	$MySQL->query("INSERT INTO last_visited (accountid, area, last_visited) VALUES ('".$user->ID."', 'jail_control', NOW()) ON DUPLICATE KEY UPDATE last_visited = NOW()");
	
	$result_prepare = $MySQL->fetch_complete("SELECT TIMEDIFF(NOW(), call_time) as age, UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(call_time) as call_secs, call_id, charid, charid_accusator, call_type, status, responsible, message FROM server.calls WHERE status = 1 ORDER BY call_time DESC");
	$result_calls = array();
	foreach($result_prepare as $item) {
		$result_prepare2 = array_merge($item, $MySQL->query_first("SELECT server.chars.name as char_name, server.chars.online as online, web.accounts.name as account_name, web.accounts.accountid as accountid FROM (server.chars LEFT JOIN web.accounts ON server.chars.accountid = web.accounts.accountid) WHERE charid = ".intval($item['charid'])));
		$result_prepare2 = array_merge($result_prepare2,(array)$MySQL->query_first("SELECT online as account_online FROM server.chars WHERE accountid = '".intval($result_prepare2['accountid'])."' LIMIT 0,1"));
		$result_prepare2 = array_merge($result_prepare2,(array)$MySQL->query_first("SELECT name as responsible_account_name FROM web.accounts WHERE accountid = ".intval($item['responsible'])));
		$result_prepare2 = array_merge($result_prepare2,(array)$MySQL->query_first("SELECT online as responsible_account_online FROM server.chars WHERE accountid = '".intval($item['responsible'])."' LIMIT 0,1"));			
		if($item['call_type']=='B') {
			$result_prepare2 = array_merge($result_prepare2,$MySQL->query_first("SELECT server.chars.name as char_name_accusator, server.chars.online as online_accusator, web.accounts.name as account_name_accusator, web.accounts.accountid as accountid_accusator FROM (server.chars LEFT JOIN web.accounts ON server.chars.accountid = web.accounts.accountid) WHERE charid = ".intval($item['charid_accusator'])));
			$result_prepare2 = array_merge($result_prepare2,(array)$MySQL->query_first("SELECT online as accusator_account_online FROM server.chars WHERE accountid = '".intval($result_prepare2['accountid_accusator'])."' LIMIT 0,1"));
		}
		$result_calls[] = $result_prepare2;
	}
	$Smarty->assign( 'result_calls', $result_calls );
	$page['content'] = $Smarty->fetch( 'jail_control.tpl' );
}


$Smarty->assign( 'page', $page );
$Smarty->display( 'main.tpl' );
	
?>