<?php

include './core.php';

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

if( isset( $_REQUEST['edit'] ) )
{
    if( isset( $_POST['send_form'] ) )
    {
    	$MySQL->query( "UPDATE applications SET state = '".$_POST['state']."', comment = '".$_POST['comment']."', lastchange = ".time()." WHERE applicationID = ".intval( $_POST['edit'] ) );
    }

    $application = $MySQL->query_first( "SELECT applications.*, server.accounts.name, server.accounts.email, server.accounts.icq AS icq2 FROM applications, server.accounts WHERE server.accounts.accountid = applications.accountid && applications.applicationID = ".intval( $_REQUEST['edit'] ) );
    $application['viewurl'] = combine_path( CORE_URL, 'applications_view.php?view='.$application['applicationID'] );
    $oapps = $MySQL->fetch_complete( "SELECT applications.* FROM applications, server.accounts WHERE server.accounts.accountid = applications.accountid && ( applications.accountid = ".$application['accountid']." || server.accounts.email = '".$application['email']."' ) && applicationID != ".$application['applicationID']." ORDER BY date" );
    $Smarty->assign( 'application', $application );
    $Smarty->assign( 'oapps', $oapps );

    $page['content'] = $Smarty->fetch( 'applications_admin_item.tpl' );
}
else
{
    if( isset( $_REQUEST['search_form'] ) )
	{
	    $search_conditions = array();

	    if( check_fields( 'name' ) )
	        $search_conditions[] = sprintf("server.accounts.name LIKE '%s'", me_escape( $_POST['name'] ));
	    if( check_fields( 'email' ) )
	        $search_conditions[] = sprintf("server.accounts.email LIKE '%s'", me_escape( $_POST['email'] ));
	    if( check_fields( 'icq' ) )
	        $search_conditions[] = sprintf("applications.icq LIKE '%s'", me_escape($_POST['icq']));
        if( check_fields( 'state' ) )
	        $search_conditions[] = sprintf("applications.state = '%s'", me_escape($_POST['state']));

	    $search_condstring = implode( ' &&', $search_conditions );

	    $result_applications = $MySQL->fetch_complete( sprintf("SELECT applications.*, server.accounts.name, server.accounts.email, server.accounts.icq AS icq2 FROM applications, server.accounts WHERE server.accounts.accountid = applications.accountid && %s", $search_condstring ));
	    $Smarty->assign( 'result_applications', $result_applications );
	}

    $new_applications = $MySQL->fetch_complete( "SELECT applications.*, server.accounts.name, server.accounts.email, server.accounts.icq AS icq2 FROM applications, server.accounts WHERE applications.state = 'waiting' && server.accounts.accountid = applications.accountid ORDER BY date" );
    $Smarty->assign( 'new_applications', $new_applications );

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

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

?>