<?php

/* 
 * Prevent guest users from booking before waitlists
 */

add_filter('em_bookings_is_open','my_booking_open', 100, 2);
function my_booking_open( $return, $EM_Bookings ){
  global $wpdb;
  
  if( get_option('dbem_waitlists_events')  && !is_user_logged_in()  ) {
	  
    $EM_Event = $EM_Bookings->get_event();
	
	$waitlist_events = get_option('dbem_waitlists_events_default');
	
	if ( $waitlist_events ){
		
		if (!empty($EM_Event->event_attributes['waitlist'])) {
			
		  $statuses = array(6,7);
			
		  $sql = 'SELECT SUM(booking_spaces) FROM '.EM_BOOKINGS_TABLE. ' WHERE booking_status IN ('. implode(',', $statuses) .') AND event_id=%d';
			
		  $pending_spaces = $wpdb->get_var( $wpdb->prepare($sql, $EM_Bookings->event_id) );			
		  
		  if ( $pending_spaces > 0 ){
			  
			  $return = false;
			  
		  }
		  
		}
		
	}
	  
  }
	
	
  if( get_option('dbem_waitlists_events')  && is_user_logged_in()  ) {
		
	$current_user = wp_get_current_user(); //$current_user->ID

	$statuses = array(6,7);

	$sql = 'SELECT SUM(booking_spaces) FROM '.EM_BOOKINGS_TABLE. ' WHERE booking_status IN ('. implode(',', $statuses) .') AND event_id=%d AND person_id=%d';

	$pending_spaces = $wpdb->get_var( $wpdb->prepare($sql, $EM_Bookings->event_id, $current_user->ID ) );			

	if ( $pending_spaces > 0 && !isset($_REQUEST['uuid']) ){
	  
	  $return = false;
	  
	}
		
  }

  return $return;	
}