<?php

include './core.php';

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

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

    if( !check_fields( 'age', 'group', 'experiences', 'time', 'workarea', 'rpg', 'tolkien', 'why', 'message' ) )
        $form_errors[] = form_error( 'uncomplete' );
    else
    {
        if( isset( $_POST['icq'] ) && strlen( $_POST['icq'] ) > 12 )
            $form_errors[] = form_error( 'toolong_icq' );
        if( $user->group > 0 || $user->rank > 4 )
        	$form_errors[] = form_error( 'already_staff' );

        list( $acount ) = $MySQL->query_first( sprintf("SELECT COUNT(*) FROM applications WHERE accountid = %d && state = 'waiting'", $user->ID ));
    	if( $acount > 0 )
        	$form_errors[] = form_error( 'waiting_application' );
    }

    if( count( $form_errors ) > 0 )
    {
        assign_formvalues( 'age', 'group', 'experiences', 'time', 'workarea', 'rpg', 'tolkien', 'why', 'message' );
        $Smarty->assign( 'form_errors', $form_errors );
    }
    else
    {
        if( !isset( $_POST['icq'] ) || empty( $_POST['icq'] ) )
        	$icq = 'NULL';
        else
        	$icq = sprintf("%s", me_escape($_POST['icq']));
        $MySQL->query( sprintf("INSERT INTO applications (accountid, icq, `group`, age, experiences, time, workarea, rpg, tolkien, why, message, date, state) VALUES
						(%d, '%s', %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', ".time().", 'waiting')", $user->ID, $icq, intval( $_POST['group'] ), intval( $_POST['age'] ), me_escape( $_POST['experiences'] ), me_escape( $_POST['time'] ), me_escape( $_POST['workarea'] ), me_escape( $_POST['rpg'] ), me_escape( $_POST['tolkien'] ), me_escape( $_POST['why'] ), me_escape( $_POST['message'] ) ));
    	display_message( 'application_success' );
    }
}
elseif( isset( $_REQUEST['delete_waiting'] ) )
{
	$MySQL->query( sprintf("DELETE FROM applications WHERE accountid = %d && state = 'waiting'", $user->ID));
	$Smarty->assign( 'deleted', true );
}

list( $wapp ) = $MySQL->query_first( sprintf("SELECT COUNT(*) FROM applications WHERE accountid = %d && state = 'waiting'", $user->ID));
$Smarty->assign( 'wapp', ( $wapp > 0 ) );

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

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

?>