<?php

include './core.php';

if( !isset( $user ) ) access_error();

if( isset( $_REQUEST['view'] ) )
{
    $message = $MySQL->query_first( "SELECT messages.*, server.accounts.name AS sender_name FROM messages,server.accounts WHERE ( messages.sender = 0 || messages.sender = server.accounts.accountid ) && messageID = ".intval( $_REQUEST['view'] )." && receiver = ".$user->ID );
	$Smarty->assign( 'message', $message );

    $page['content'] = $Smarty->fetch( 'messages_view.tpl' );
}
elseif( isset( $_REQUEST['markread'] ) )
{
	$MySQL->query( "UPDATE messages SET `read` = 1 WHERE messageID = ".intval( $_REQUEST['markread'] )." && receiver = ".$user->ID );
    set_location( 'messages.php?view='.intval( $_REQUEST['markread'] ).'&amp;'.SID );
}
elseif( isset( $_REQUEST['delete'] ) && isset( $_REQUEST['is_js_confirmed'] ) && $_REQUEST['is_js_confirmed'] == "1" )
{
	$MySQL->query( "DELETE FROM messages WHERE messageID = ".intval( $_REQUEST['delete'] )." && receiver = ".$user->ID );
	set_location( 'messages.php?'.SID );
}
elseif( isset($_REQUEST['action']) AND $_REQUEST['action']=='commit_staff_message' ) {
	// TODO: IG-Logging
	flood_protect( 'call' );
	$exp_time = time() + intval( $settings['flood_protect_call'] );
	$MySQL->query("INSERT INTO flood_protect SET ip_address = '".$_SERVER['REMOTE_ADDR']."', performed_action = 'call', expire = '".$exp_time."'");
	$char = $MySQL->query_first("SELECT charid FROM server.chars WHERE accountid = '".$user->ID."' AND aktiviert = 1 AND block = 0 AND charid = '".intval($_REQUEST['charid'])."'");
	if($char['charid'] == $_REQUEST['charid'] AND strlen($_REQUEST['message'])>5) {
		$MySQL->query("INSERT INTO server.calls SET charid = '".$_REQUEST['charid']."', call_time = NOW(), call_type = 'HP', status = 1, message = '".$_REQUEST['message']."'");
	}
	set_location( 'messages.php?'.SID );
}
else
{
	$messages = $MySQL->fetch_complete( "SELECT messages.*, server.accounts.name AS sender_name FROM messages,server.accounts WHERE ( messages.sender = 0 || messages.sender = server.accounts.accountid ) && messages.receiver = ".$user->ID." ORDER BY time DESC" );
    $Smarty->assign( 'messages', $messages );
    
	$chars = $MySQL->fetch_complete("SELECT charid, name FROM server.chars WHERE accountid = '".$user->ID."' AND aktiviert = 1 AND block = 0");
	if(count($chars) > 0) {
		$Smarty->assign("call_available",true);
		$Smarty->assign("chars",$chars);
	}
    
	$page['content'] = $Smarty->fetch( 'messages.tpl' );
}

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

?>