<?php
add_action( 'add_meta_boxes', 'wpas_add_parties_widget' );
/**
 * Register the metabox
 */
function wpas_add_parties_widget() {
	add_meta_box( 'wpas_parties', __('Ticket Contact', 'wpas'), 'wpas_parties_details', 'tickets', 'side', 'high' );
}

function wpas_parties_details() {
		global $post, $current_user, $wpdb;
		$assignee 		= get_post_meta( $post->ID, WPAS_PREFIX.'assignee', true );
		$ccs 			= get_post_meta( $post->ID, WPAS_PREFIX.'ccs', true );
		$issuer 		= get_userdata( $post->post_author );
		$issuer_name 	= $issuer->data->display_name;

		/* get the roles */
		global $wp_roles;

		/* Prepare the empty users list */
		$users = array();

		/* Parse the roles */
		foreach( $wp_roles->roles as $role => $data ) {

			/* Check if current role can edit tickets */
			if( array_key_exists( 'edit_ticket', $data['capabilities'] ) ) {

				/* Get users with current role */
				$usrs = new WP_User_Query( array( 'role' => $role ) );

				/* Save users in global array */
				$users = array_merge( $users, $usrs->get_results() );
			}
		}
		?>
		<table class="form-table">
			<tbody>
				<tr valign="top">
					<td style="width:50%">
						<label for="issuer"><strong><?php _e('Issuer', 'wpas'); ?></strong></label><br/>
						<a id="issuer" href="<?php echo admin_url( add_query_arg( array( 'post_type' => 'tickets', 'author' => $issuer->data->ID ), 'edit.php' ) ); ?>"><?php echo $issuer_name; ?></a>
					</td>
					<td style="width:50%">
						<label for="assignee"><strong><?php _e('Assignee', 'wpas'); ?></strong></label>
						<select name="assignee" id="assignee" <?php if( !current_user_can('assign_ticket') ) { echo 'disabled'; } ?> style="width:100%">
							<?php
							foreach( $users as $usr => $data ) {
								?><option value="<?php echo $data->ID; ?>" <?php if( $data->ID == $assignee || '' == $assignee && $current_user->data->ID == $data->ID ) { echo 'selected="selected"'; } ?>><?php echo $data->data->display_name; ?></option><?php
							}
							?>
						</select>
					</td>
				</tr>
				<tr valign="top">
					<td colspan="2">
						<label for="ccs"><strong><?php _e('CCs', 'wpas'); ?></strong></label>
						<input type="text" id="ccs" name="ccs" value="<?php echo $ccs; ?>" style="width:100%" />
					</td>
				</tr>
			</tbody>
		</table>
	<?php }