<?php

include './core.php';

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

if( isset( $_POST['send_form'] ) )
{
    $form_errors = array();

    if( !check_fields( 'receiver', 'subject', 'message' ) )
        $form_errors[] = form_error( 'uncomplete' );
    else
    {
        if( strlen( $_POST['subject'] ) > 255 )
            $form_errors[] = form_error( 'toolong_topic' );

        $receiver = new Account( $_POST['receiver'] );

        if( !isset( $receiver ) || $receiver == null || $receiver->ID <= 0 )
        	$form_errors[] = form_error( 'bad_user' );
    }

    if( count( $form_errors ) > 0 )
    {
        $Smarty->assign( 'form_errors', $form_errors );
        assign_formvalues( 'receiver', 'subject', 'message' );
    }
    else
    {
    	$MySQL->query( sprintf("INSERT INTO messages (sender, receiver, time, subject, message) VALUES (%d, %d, ".time().", '%s', '%s')", $user->ID, $receiver->ID, me_escape( $_POST['subject'] ), me_escape( $_POST['message'] ) ));

        $Smarty->assign( 'sended', true );
    }
}

$page['content'] = $Smarty->fetch( 'send_message.tpl' );

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

?>