<?php
/**
 * RSVP PRO Attendees list table
 *
 * @version 4.4.8
 */

class RSVP_Pro_Attendees_List_Table extends RSVP_PRO_List_Table {

	public function __construct( $args = array() ){

		parent::__construct( array(
				'plural'   => 'attendees',
				'singular' => 'attendee',
				'ajax'     => false,
				'screen'   => null,
		) );
	}


	/**
	 * Message to be displayed when there are no items
	 *
	 * @since  4.4.8
	 * @access public
	 */
	public function no_items(){
		_e( 'No attendees found.', 'rsvp-pro-plugin' );
	}


	public function prepare_items(){

		global $wpdb;
		$eventID                      = $_GET['eventID'];
		$isSubEvent                   = false;
		$subEventID                   = 0;
		$search_fields                = rsvp_pro_admin_get_search_fields( $eventID );
		$previous_searches            = array();
		$global_attendee_list_enabled = ( get_option( RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST ) == 'Y' ) ? true : false;

		if ( ( $eventID <= 0 ) && ( $eventID != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ){
			rsvp_pro_admin_eventList();
			exit;
		}

		// Check to see if there is a parent event...
		$sql           = 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
		$parentEventID = $wpdb->get_var( $wpdb->prepare( $sql, $eventID ) );

		if ( $parentEventID > 0 ){
			$subEventID = $eventID;
			$isSubEvent = true;
		}

		$sql          = 'SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, a.rsvpStatus) as rsvpStatus, note, ' .
						'additionalAttendee, personalGreeting, passcode, alternate_passcode, email, IFNULL(se.rsvpDate, a.rsvpDate) as rsvpDate, 
		IFNULL(se.checked_in, a.checked_in) AS checked_in ' .
						'FROM ' . PRO_ATTENDEES_TABLE . ' a
		INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = a.rsvpEventID
		LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d  ';
		$where_clause = ' WHERE ( (a.rsvpEventID = %d) ';

		if ( $global_attendee_list_enabled ){
			$where_clause .= ' OR (a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ') ';
		}


		if ( $isSubEvent ) {

			$sql = "SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, a.rsvpStatus) AS rsvpStatus, note, " .
				   'additionalAttendee, personalGreeting, passcode, alternate_passcode, email, a.rsvpDate, se.checked_in ' .
				   'FROM ' . PRO_ATTENDEES_TABLE . ' a
			INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = %d
			LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d ';

			$where_clause .= ' OR (a.rsvpEventID = %d)';
		}

		$where_clause .= " ) AND (((SELECT IFNULL(event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "' ) FROM " . PRO_EVENT_TABLE . " WHERE id = %d) != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = %d)))';

		$s      = isset( $_GET['s'] ) ? $_GET['s'] : '';
		$values = array();

		if ( $isSubEvent ){
			$values = array( $subEventID, $subEventID,$subEventID, $parentEventID, $subEventID, $subEventID, $s );
		} else {
			$values = array( $eventID, $eventID, $eventID, $eventID, $s );
		}

		if ( isset( $_GET['search_field'] ) && array_key_exists( $_GET['search_field'], $search_fields ) ){
			if ( strpos( $_GET['search_field'], 'cq_' ) !== false ){
				$cq_id = str_replace( 'cq_', '', $_GET['search_field'] );

				if ( is_numeric( $cq_id ) && ( $cq_id > 0 ) ){
					$where_clause .= ' AND a.id IN (SELECT attendeeID FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = ' . $cq_id . " AND answer LIKE '%%%s%%' ) ";
				}
			} else {
				if ( $isSubEvent && ( $_GET['search_field'] == 'rsvpStatus' ) ){
					$where_clause .= ' AND ( a.' . esc_sql( $_GET['search_field'] ) . " = '%s' ) ";
				} elseif ( $_GET['search_field'] == 'rsvpStatus' ) {
					$where_clause .= ' AND ( (a.' . esc_sql( $_GET['search_field'] ) . " = '%s') OR (se." . esc_sql( $_GET['search_field'] ) . " = '%s') ) ";
					$values[]     = $s;
				} else {
					$where_clause .= ' AND ( ' . esc_sql( $_GET['search_field'] ) . " LIKE '%%%s%%' ) ";
				}
			}
		} else {
			$where_clause .= " AND ( firstName LIKE '%%%s%%'  OR  lastName LIKE '%%%s%%' )";
			$values[]     = $s;

		}

		$order_by = isset( $_REQUEST['orderby'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['orderby'] ) ) : ' firstName';
		$order   = isset( $_REQUEST['order'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['order'] ) ) : 'ASC';

		$sql .= $where_clause . ' ORDER BY ' . $order_by . ' ' . $order;

		if ( $_POST && isset( $_POST['paged'] ) ){
			$pagenum = $_POST['paged'];
		} else {
			$pagenum = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
		}

		$screen_options = get_user_meta( get_current_user_id(), 'rsvp_screen_options' );
		$pagesize       = ( $screen_options && isset( $screen_options[0]['pagesize'] ) ) ? $screen_options[0]['pagesize'] : 25;
		$offset         = 0;

		if ( isset( $_GET['pagesize'] ) ){
			$limit = $_GET['pagesize'];
		} else {
			$limit = $pagesize;
		}

		$offset    = ( $pagenum - 1 ) * $limit;
		$sql_limit = " LIMIT $offset, $limit ";

		$columns  = $this->get_columns();
		$hidden   = $this->get_hidden_columns();
		$sortable = $this->get_sortable_columns();

		$data = $wpdb->get_results( $wpdb->prepare( $sql . $sql_limit, $values ), ARRAY_A  );

		$total        = $wpdb->get_results( $wpdb->prepare( $sql, $values ) );
		$num_of_pages = ceil( count( $total ) / $limit );

		$args['total_pages'] = $num_of_pages;
		$args['total_items'] = count( $total );

		$this->_pagination_args = $args;

		$this->_column_headers = array( $columns, $hidden, $sortable );

		$data = apply_filters( 'rsvp_pro_attendees_list_views', $data );

		$this->items = $this->prepare_attendees( $data, $eventID );

	}

	public function get_columns() {

		$rsvp_helper = RSVP_PRO_Admin_Helper::get_instance();
		$global_attendee_list_enabled = ( get_option( RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST ) == 'Y' ) ? true : false;

		$event_columns = $rsvp_helper->get_event_meta( $_GET['eventID'], 'attendee_columns' );

		$event_columns = ! empty( $event_columns[0]->attendee_columns ) ? explode( ',', $event_columns[0]->attendee_columns ) : false;

		$columns      = array();
		$column_names = apply_filters( 'rsvp_pro_column_names', array(
				'attendee_name'        => __( 'Attendee', 'rsvp-pro-plugin' ),
				'rsvp_status'          => __( 'RSVP Status', 'rsvp-pro-plugin' ),
				'rsvp_date'            => __( 'RSVP Date', 'rsvp-pro-plugin' ),
				'additional_attendee'  => __( 'Additional Attendee', 'rsvp-pro-plugin' ),
				'note'                 => __( 'Note', 'rsvp-pro-plugin' ),
				'associated_attendees' => __( 'Associated Attendees', 'rsvp-pro-plugin' ),
				'email'                => __( 'Email', 'rsvp-pro-plugin' ),
				'checked_in'           => __( 'Checked in', 'rsvp-pro-plugin' ),
				'passcode'             => __( 'Passcode', 'rsvp-pro-plugin' ),
				'alternate_passcode'   => __( 'Alternate passcode', 'rsvp-pro-plugin' )
		) );

		$columns['cb'] = __( 'ID', 'rsvp-pro-plugin' );

		if ( $event_columns && ! empty( $event_columns ) && ! $global_attendee_list_enabled ){
			foreach ( $event_columns as $e_col ){
				if ( isset( $column_names[ $e_col ] ) ){
					$columns[ $e_col ] = $column_names[ $e_col ];
				} else {
					$question_id = (int)preg_replace( '/[^\-\d]*(\-?\d*).*/', '$1', $e_col );
					$question    = $rsvp_helper->get_custom_question( $_GET['eventID'], $question_id );
					if ( $question ){
						$columns[ $e_col ] = $question[0]->question;
					}

				}

			}
		} else {
			$columns['attendee_name']       = __( 'Attendee', 'rsvp-pro-plugin' );
			$columns['rsvp_status']         = __( 'RSVP Status', 'rsvp-pro-plugin' );
			$columns['rsvp_date']           = __( 'RSVP Date', 'rsvp-pro-plugin' );
			$columns['additional_attendee'] = __( 'Additional Attendee', 'rsvp-pro-plugin' );
		}

		return $columns;
	}

	public function get_hidden_columns(){
		return array();
	}

	public function get_sortable_columns(){
		return array(
				'attendee_name' => array( 'firstName', false ),
				'rsvp_status'   => array( 'rsvpStatus', false ),
				'rsvp_date'     => array( 'rsvpDate', false ),
		);
	}

	/**
	 * Sorting function
	 *
	 * @param $a
	 * @param $b
	 *
	 * @return int
	 * @since 4.4.8
	 */
	public function usort_reorder( $a, $b ){
		// If no sort, default to name
		$orderby = ( !empty( $_GET['orderby'] ) ) ? $_GET['orderby'] : 'attendee_name';

		// If no order, default to asc
		$order = ( !empty( $_GET['order'] ) ) ? $_GET['order'] : 'asc';

		// Determine sort order
		if ( 'attendee_name' == $orderby ){
			$result = $this->attendee_orderby( $a, $b );
		} else {
			$result = strcasecmp( $a[ $orderby ], $b[ $orderby ] );
		}

		// Send final sort direction to usort
		return ( $order === 'asc' ) ? $result : -$result;
	}

	/**
	 * Sorting function
	 *
	 * @param $a
	 * @param $b
	 *
	 * @return int
	 * @since 4.4.8
	 */
	public function attendee_orderby( $a, $b ){

		if ( $a["firstName"] == $b["firstName"] ){
			return strcmp( $a["lastName"], $b["lastName"] );
		} else {
			return strcmp( $a["firstName"], $b["firstName"] );
		}

	}

	/**
	 * The Attendee column output
	 *
	 * @param $item
	 *
	 * @since 4.4.8
	 */
	public function column_attendee_name( $item ){

		// Edit link
		$edit_link = add_query_arg( array(
				'page'    => 'rsvp-pro-top-level',
				'action'  => 'modify_attendee',
				'eventID' => $item['eventID'],
				'id'      => $item['id']
		), admin_url( 'admin.php' ) );

		// Delete link
		$delete_link = add_query_arg( array(
				'action' => 'delete-rsvp-pro-attendee',
				'id'     => absint( $item['id'] )
		), admin_url( 'admin.php' ) );

		echo '<a class="row-title" href="' . $edit_link . '">' . esc_html( $item['firstName'] . ' ' . $item['lastName'] ) . '</a>';

		// Assemble links

		$actions           = array();
		$actions['edit']   = '<a href="' . $edit_link . '">' . __( 'Edit', 'rsvp-pro-plugin' ) . '</a>';
		$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( $delete_link, 'delete-rsvp-pro-attendee_' . absint( $item['id'] ) ) . "' onclick=\"if ( confirm( '" . esc_js( sprintf( __( 'Delete "%s"?', 'rsvp-pro-plugin' ), esc_html( $item['firstName'] . ' ' . $item['lastName'] ) ) ) . "' ) ) { return true;} return false;\">" . __( 'Delete', 'rsvp-pro-plugin' ) . '</a>';

		$actions = apply_filters( 'rsvp_pro_attendees_actions', $actions, $item );

		echo $this->row_actions( $actions );
	}

	public function column_default( $item, $column_name ){
		$text = '';
		switch ( $column_name ){

			case 'attendee_name':

				$text = esc_html( $item['firstName'] . ' ' . $item['lastName'] );
				break;
			case 'rsvp_status':
				$text = ( isset( $item[ $column_name ] ) && $item[ $column_name ] && 'NoResponse' != $item[ $column_name ] ) ? $item[ $column_name ] : esc_html__( 'No response', 'rsvp-pro-plugin' );
				break;
			case 'rsvp_date':
				if ( isset( $item[ $column_name ] ) && $item[ $column_name ] ){
					$text = date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $item[ $column_name ] ) );
				} else {
					$text = esc_html__( 'No date set', 'rsvp-pro-plugin' );
				}
				break;
			case 'additional_attendee':
				$text = ( isset( $item['additionalAttendee'] ) && $item[ $column_name ] && 'Y' == $item[ $column_name ] ) ? esc_html__( 'Yes', 'rsvp-pro-plugin' ) : esc_html__( 'No', 'rsvp-pro-plugin' );
				break;
			case 'associated_attendees':
				$rsvp_helper  = RSVP_PRO_Admin_Helper::get_instance();
				$associations = $rsvp_helper->get_associated_attendees( $item['id'] );
				foreach ( $associations as $a ){
					$text .= htmlspecialchars( stripslashes( $a->name ) ) . '<br />';
				}
				break;
			default:
				if ( isset( $item[ $column_name ] ) ){
					$text = esc_html( $item[ $column_name ] );
				} else {
					// First check to see if it is custom question
					$rsvp_helper     = RSVP_PRO_Admin_Helper::get_instance();
					$question_id     = (int)preg_replace( '/[^\-\d]*(\-?\d*).*/', '$1', $column_name );
					$custom_question = $rsvp_helper->get_custom_question( $_GET['eventID'], $question_id );

					// If questino, check for answer
					if ( $custom_question && !empty( $custom_question ) ){
						$custom_answer = $rsvp_helper->get_custom_answer( $question_id, $item['id'] );

						// If answer, show it
						if ( $custom_answer && !empty( $custom_answer ) ){
							$text = esc_html( $custom_answer[0]->answer );
						}
					}
				}
		}

		return apply_filters( "rsvp_pro_attendee_list_column_$column_name", $text, $item );
	}


	/**
	 * Display the table
	 *
	 * @since  4.4.8
	 * @access public
	 */
	public function display(){
		$singular = $this->_args['singular'];
		$this->prepare_items();
		$event_id       = $_GET['eventID'];
		$search_fields  = rsvp_pro_admin_get_search_fields( $_GET['eventID'] );
		$screen_options = get_user_meta( get_current_user_id(), 'rsvp_screen_options' );

		if ( $screen_options && isset( $screen_options[0]['pagesize'] ) ){
			$pagesize = $screen_options[0]['pagesize'];
		} else {
			$pagesize = 25;
		}

		?>
		<form id="posts-filter" method="get">
			<p class="search-box">
				<select name="search_field" id="attendee_search_field" size="1">
					<option value=""><?php echo rsvp_pro_get_admin_string( 'field_to_search_label' ); ?></option>
					<?php foreach ( $search_fields as $key => $value ){ ?>
						<option value="<?php echo $key; ?>"><?php echo esc_html( $value ); ?></option>
					<?php } ?>
				</select>
				<label class="screen-reader-text"
					   for="post-search-input"><?php esc_html_e( 'Search', 'rsvp-pro-plugin' ); ?></label>
				<input type="search" id="post-search-input" name="s"
					   value="<?php echo( isset( $_GET['s'] ) && !empty( $_GET['s'] ) ? $_GET['s'] : '' ) ?>">
				<input type="hidden" name="page" value="rsvp-pro-top-level">
				<input type="hidden" id="post-pagesize" name="pagesize"
					   value="<?php echo( isset( $_GET['pagesize'] ) && !empty( $_GET['pagesize'] ) ? $_GET['pagesize'] : $pagesize ) ?>">
				<input type="hidden" name="action" value="attendees">
				<input type="hidden" name="eventID" value="<?php echo $event_id; ?>">
				<input type="hidden" name="event_list"
					   value="<?php echo( isset( $_GET['event_list'] ) ? $_GET['event_list'] : 'all' ); ?>">
				<input type="submit" id="search-submit" class="button"
					   value="<?php esc_html_e( 'Search attendee', 'rsvp-pro-plugin' ); ?>">
			</p>
			<?php
			$this->display_tablenav( 'top' );
			?>
			<table class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
				<thead>
				<tr>
					<?php $this->print_column_headers(); ?>
				</tr>
				</thead>

				<tbody id="the-list"<?php
				if ( $singular ){
					echo " data-wp-lists='list:$singular'";
				} ?>>
				<?php $this->display_rows_or_placeholder(); ?>
				</tbody>

				<tfoot>
				<tr>
					<?php $this->print_column_headers( false ); ?>
				</tr>
				</tfoot>

			</table>
			<?php
			$this->display_tablenav( 'bottom' );
			?>
		</form>
		<?php
	}

	/**
	 * @param $attendees
	 * @param $eventID
	 *
	 * @return mixed
	 */
	public function prepare_attendees( $attendees, $eventID ){

		$return = array();

		foreach ( $attendees as $attendee ){

			$return[ $attendee['id'] ] = array(
					'id'                  => $attendee['id'],
					'firstName'           => $attendee['firstName'],
					'lastName'            => $attendee['lastName'],
					'rsvp_status'         => $attendee['rsvpStatus'],
					'rsvp_date'           => $attendee['rsvpDate'],
					'additional_attendee' => $attendee['additionalAttendee'],
					'note'                => $attendee['note'],
					'email'               => $attendee['email'],
					'passcode'            => $attendee['passcode'],
					'alternate_passcode'  => $attendee['alternate_passcode'],
					'checked_in'          => $attendee['checked_in'],
					'eventID'             => $eventID,
			);
		}

		return $return;

	}

	/**
	 * Handles the checkbox column output.
	 *
	 * @param $item
	 *
	 * @since 4.4.8
	 */
	public function column_cb( $item ){
		?>
		<input id="cb-select-<?php echo absint( $item['id'] ); ?>" type="checkbox" name="attendee[]"
			   value="<?php echo absint( $item['id'] ); ?>"/>
		<div class="locked-indicator">
			<span class="locked-indicator-icon" aria-hidden="true"></span>
		</div>
		<?php

	}


	/**
	 * Display the pagination.
	 *
	 * @param string $which
	 *
	 * @since  4.4.8
	 * @access protected
	 *
	 */
	protected function pagination( $which ){

		if ( empty( $this->_pagination_args ) ){
			return;
		}
		$total_items     = $this->_pagination_args['total_items'];
		$total_pages     = $this->_pagination_args['total_pages'];
		$infinite_scroll = false;
		if ( isset( $this->_pagination_args['infinite_scroll'] ) ){
			$infinite_scroll = $this->_pagination_args['infinite_scroll'];
		}

		$output = '<span class="displaying-num">' . sprintf( _n( '1 item', '%s items', $total_items, 'rsvp-pro-plugin' ), number_format_i18n( $total_items ) ) . '</span>';

		$current = $this->get_pagenum();

		$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );

		$current_url = remove_query_arg( array( 'hotkeys_highlight_last', 'hotkeys_highlight_first' ), $current_url );

		$page_links = array();

		$disable_first = $disable_last = '';
		if ( $current == 1 ){
			$disable_first = ' disabled';
		}
		if ( $current == $total_pages ){
			$disable_last = ' disabled';
		}
		$page_links[] = sprintf(
				"<a class='%s' title='%s' href='%s'>%s</a>",
				'first-page button' . $disable_first,
				esc_attr__( 'Go to the first page', 'rsvp-pro-plugin' ),
				esc_url( remove_query_arg( 'paged', $current_url ) ),
				'&laquo;'
		);

		$page_links[] = sprintf(
				"<a class='%s' title='%s' href='%s'>%s</a>",
				'prev-page button' . $disable_first,
				esc_attr__( 'Go to the previous page', 'rsvp-pro-plugin' ),
				esc_url( add_query_arg( 'paged', max( 1, $current - 1 ), $current_url ) ),
				'&lsaquo;'
		);

		if ( 'bottom' == $which ){
			$html_current_page = $current;
		} else {
			$html_current_page = sprintf(
					"%s<input class='current-page' id='current-page-selector' title='%s' type='text' name='paged' value='%s' size='%d'>",
					'<label for="current-page-selector" class="screen-reader-text">' . __( 'Select Page', 'rsvp-pro-plugin' ) . '</label>',
					esc_attr__( 'Current page', 'rsvp-pro-plugin' ),
					$current,
					strlen( $total_pages )
			);
		}
		$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
		$page_links[]     = '<span class="paging-input">' . sprintf( _x( '%1$s of %2$s', 'paging', 'rsvp-pro-plugin' ), $html_current_page, $html_total_pages ) . '</span>';

		$page_links[] = sprintf(
				"<a class='%s' title='%s' href='%s'>%s</a>",
				'next-page button' . $disable_last,
				esc_attr__( 'Go to the next page', 'rsvp-pro-plugin' ),
				esc_url( add_query_arg( 'paged', min( $total_pages, $current + 1 ), $current_url ) ),
				'&rsaquo;'
		);

		$page_links[] = sprintf(
				"<a class='%s' title='%s' href='%s'>%s</a>",
				'last-page button' . $disable_last,
				esc_attr__( 'Go to the last page', 'rsvp-pro-plugin' ),
				esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ),
				'&raquo;'
		);

		$pagination_links_class = 'pagination-links';
		if ( !empty( $infinite_scroll ) ){
			$pagination_links_class = ' hide-if-js';
		}
		$output .= "\n<span class='$pagination_links_class'>" . implode( "\n", $page_links ) . '</span>';

		if ( $total_pages ){
			$page_class = $total_pages < 2 ? ' one-page' : '';
		} else {
			$page_class = ' no-pages';
		};
		$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";

		echo $this->_pagination;
	}

	/**
	 * Print column headers, accounting for hidden and sortable columns.
	 *
	 * @param bool $with_id Whether to set the id attribute or not
	 *
	 * @since  4.4.8
	 * @access public
	 *
	 */
	public function print_column_headers( $with_id = true ){
		list( $columns, $hidden, $sortable ) = $this->get_column_info();

		$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
		$current_url = remove_query_arg( 'paged', $current_url );

		if ( isset( $_GET['orderby'] ) ){
			$current_orderby = $_GET['orderby'];
		} else {
			$current_orderby = '';
		}

		if ( isset( $_GET['order'] ) && 'desc' === $_GET['order'] ){
			$current_order = 'desc';
		} else {
			$current_order = 'asc';
		}

		if ( !empty( $columns['cb'] ) ){
			static $cb_counter = 1;
			$columns['cb'] = '<label class="screen-reader-text" for="cb-select-all-' . $cb_counter . '">' . esc_html__( 'Select All', 'rsvp-pro-plugin' ) . '</label>'
							 . '<input id="cb-select-all-' . $cb_counter . '" type="checkbox" />';
			$cb_counter++;
		}

		foreach ( $columns as $column_key => $column_display_name ){
			$class = array( 'manage-column', "column-$column_key" );

			if ( in_array( $column_key, $hidden, true ) ){
				$class[] = 'hidden';
			}

			if ( 'cb' === $column_key ){
				$class[] = 'check-column';
			} elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ), true ) ) {
				$class[] = 'num';
			}

			if ( isset( $sortable[ $column_key ] ) ){
				list( $orderby, $desc_first ) = $sortable[ $column_key ];

				if ( $current_orderby === $orderby ){
					$order = 'asc' === $current_order ? 'desc' : 'asc';

					$class[] = 'sorted';
					$class[] = $current_order;
				} else {
					$order = strtolower( $desc_first );

					if ( !in_array( $order, array( 'desc', 'asc' ), true ) ){
						$order = $desc_first ? 'desc' : 'asc';
					}

					$class[] = 'sortable';
					$class[] = 'desc' === $order ? 'asc' : 'desc';
				}

				$column_display_name = sprintf(
						'<a href="%s"><span>%s</span><span class="sorting-indicator"></span></a>',
						esc_url( add_query_arg( compact( 'orderby', 'order' ), $current_url ) ),
						$column_display_name
				);
			}

			$tag   = ( 'cb' === $column_key ) ? 'td' : 'th';
			$scope = ( 'th' === $tag ) ? 'scope="col"' : '';
			$id    = $with_id ? "id='$column_key'" : '';

			if ( !empty( $class ) ){
				$class = "class='" . implode( ' ', $class ) . "'";
			}

			echo "<$tag $scope $id $class>$column_display_name</$tag>";
		}
	}

	/**
	 * Get the current page number
	 *
	 * @return int
	 * @since  4.4.8
	 * @access public
	 *
	 */
	public function get_pagenum(){
		$pagenum = isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 0;

		if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] ){
			$pagenum = $this->_pagination_args['total_pages'];
		}

		return max( 1, $pagenum );
	}

	/**
	 * Set bulk actions
	 *
	 * @return array
	 * @Since 4.4.8
	 */
	public function get_bulk_actions(){

		$actions = array(
				'delete'   => __( 'Delete', 'rsvp-pro-plugin' ),
				'check_in' => __( 'Check in', 'rsvp-pro-plugin' )
		);

		return $actions;
	}

	/**
	 * Get an associative array ( id => link ) with the list
	 * of views available on this table.
	 *
	 * @return array
	 * @since  4.4.8
	 * @access protected
	 *
	 */
	protected function get_views(){
		global $wpdb;
		$isSubEvent                   = false;
		$subEventID                   = 0;
		$sql                          = 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
		$eventID                      = $_GET['eventID'];
		$parentEventID                = $wpdb->get_var( $wpdb->prepare( $sql, $eventID ) );
		$global_attendee_list_enabled = ( get_option( RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST ) == 'Y' ) ? true : false;

		if ( $parentEventID > 0 ){
			$subEventID = $eventID;
			$isSubEvent = true;
		}
		if ( $isSubEvent ){
			$baseSql = 'SELECT COUNT(*)
    					FROM ' . PRO_ATTENDEES_TABLE . ' a
    					LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
    					LEFT JOIN ' . PRO_EVENT_TABLE . " e ON e.id = %d
    					WHERE ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id))) AND ';

			$rsvp_event_where = ' ( ( a.rsvpEventID = %d ) OR ( a.rsvpEventID = %d ) ';
			if ( $global_attendee_list_enabled ) {
				$rsvp_event_where .= ' OR ( a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ') ';
			}
			$rsvp_event_where .= ')';

			$all_sql          = $baseSql . $rsvp_event_where;

			$all              = $wpdb->get_var( $wpdb->prepare( $all_sql, $subEventID, $subEventID, $subEventID,  $parentEventID ) );

			$sql        = $baseSql . " (se.rsvpStatus = 'Yes' OR se.rsvpStatus = 'PlusOne') AND " . $rsvp_event_where;
			$yesResults = $wpdb->get_var( $wpdb->prepare( $sql, $subEventID, $subEventID, $subEventID, $parentEventID ) );

			$sql       = $baseSql . " se.rsvpStatus = 'No' AND " . $rsvp_event_where;

			$noResults = $wpdb->get_var( $wpdb->prepare( $sql, $subEventID, $subEventID, $subEventID, $parentEventID ) );
			
			// We do this as if they say yes, plus one we will want to double the yes count...
			if ( rsvp_pro_get_event_option( $parentEventID, RSVP_PRO_OPTION_PLUS_ONE_ENABLED ) === 'Y' ) {
				$sql         = $baseSql . " se.rsvpStatus = 'PlusOne' AND " . $rsvp_event_where;
				$yesResults += $wpdb->get_var( $wpdb->prepare( $sql, $subEventID, $subEventID, $subEventID, $parentEventID ) );
			}

			$sql = $baseSql . " (se.rsvpStatus = 'NoResponse' OR se.rsvpStatus IS NULL) AND ". $rsvp_event_where . ' GROUP BY ea.rsvpAttendeeID';
			if ( rsvp_pro_get_event_information( $subEventID, RSVP_PRO_INFO_EVENT_ACCESS ) == RSVP_PRO_PRIVATE_EVENT_ACCESS ) {
				$sql = 'SELECT COUNT(*) FROM ' . PRO_EVENT_ATTENDEE_TABLE . ' ea
                            LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = ea.rsvpAttendeeID
                            JOIN ' . PRO_ATTENDEES_TABLE . " a ON a.id = ea.rsvpAttendeeID
                            WHERE (se.rsvpStatus IS NULL OR se.rsvpStatus = 'NoResponse') AND ea.rsvpEventID = %d 
                            AND " . $rsvp_event_where . ' GROUP BY ea.rsvpAttendeeID';
			}
			$temp_no_results = $wpdb->get_results( $wpdb->prepare( $sql, $subEventID, $subEventID, $parentEventID ) );
			
			$noResponseResults =  is_array( $temp_no_results ) ? count( $temp_no_results ) : 0;

			if ( rsvp_pro_get_event_option( $parentEventID, RSVP_PRO_OPTION_PLUS_ONE_ENABLED ) === 'Y' ) {
				$sql               .= " AND a.plus_one = 'Y'";
				$noResponseResults += $wpdb->get_var( $wpdb->prepare( $sql, $subEventID, $parentEventID ) );
			}
		} else {
			$baseSql = 'SELECT COUNT(*) FROM ' . PRO_ATTENDEES_TABLE . ' a
    					JOIN ' . PRO_EVENT_TABLE . " e ON e.id = a.rsvpEventID
    					WHERE ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id))) ';

			$allsql = $baseSql . " AND rsvpEventID = %d";

			$all               = $wpdb->get_var( $wpdb->prepare( $allsql, $eventID ) );
			$yesResults        = $wpdb->get_var( $wpdb->prepare( $baseSql . " AND (rsvpStatus = 'Yes' OR rsvpStatus = 'PlusOne') AND rsvpEventID = %d", $eventID ) );
			$noResults         = $wpdb->get_var( $wpdb->prepare( $baseSql . " AND rsvpStatus = 'No' AND rsvpEventID = %d", $eventID ) );
			$noResponseResults = $wpdb->get_var( $wpdb->prepare( $baseSql . " AND rsvpStatus = 'NoResponse' AND rsvpEventID = %d", $eventID ) );
			//$waitListCount     = $wpdb->get_var( $wpdb->prepare( $baseSql . " AND rsvpStatus = 'Waitlist' AND rsvpEventID = %d", $eventID ) );
			//$maybeCount        = $wpdb->get_var( $wpdb->prepare( $baseSql . " AND rsvpStatus = 'Maybe' AND rsvpEventID = %d", $eventID ) );

			// We do this as if they say yes, plus one we will want to double the yes count...
			if ( rsvp_pro_get_event_option( $eventID, RSVP_PRO_OPTION_PLUS_ONE_ENABLED ) === 'Y' ){
				$sql        = $baseSql . " AND rsvpStatus = 'PlusOne' AND rsvpEventID = %d";
				$yesResults += $wpdb->get_var( $wpdb->prepare( $sql, $eventID ) );
			}

			if ( $global_attendee_list_enabled ){
				$rsvp_event_where = ' AND ( a.rsvpEventID = %d OR a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ' )';

				// Baza: numără DISTINCT a.id ca să eviți dublurile din JOIN-uri.
				$baseSql = 'SELECT COUNT(DISTINCT a.id) FROM ' . PRO_ATTENDEES_TABLE . ' a 
							LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se 
								ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d 
							LEFT JOIN ' . PRO_EVENT_TABLE . " e 
								ON e.id = se.rsvpEventID
							WHERE (
								(IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "')
								OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . " WHERE rsvpEventID = e.id))
							)";

				$allsql = $baseSql . $rsvp_event_where;
				$all    = $wpdb->get_var( $wpdb->prepare( $allsql, $eventID, $eventID ) );

				$sql        = $baseSql . " AND (se.rsvpStatus = 'Yes' OR se.rsvpStatus = 'PlusOne')" . $rsvp_event_where;
				$yesResults = (int) $wpdb->get_var( $wpdb->prepare( $sql, $eventID, $eventID ) );

				$sql       = $baseSql . " AND se.rsvpStatus = 'No'" . $rsvp_event_where;
				$noResults = (int) $wpdb->get_var( $wpdb->prepare( $sql, $eventID, $eventID ) );

				$sql = $baseSql . 
					" AND (
							((a.rsvpStatus = 'NoResponse' OR a.rsvpStatus IS NULL) AND a.rsvpEventID = %d)
							OR
							((se.rsvpStatus = 'NoResponse' OR se.rsvpStatus IS NULL) AND a.rsvpEventID = " . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ")
						)" . $rsvp_event_where;

				$noResponseResults = (int) $wpdb->get_var( $wpdb->prepare( $sql, $eventID, $eventID, $eventID ) );

				if ( rsvp_pro_get_event_option( $eventID, RSVP_PRO_OPTION_PLUS_ONE_ENABLED ) === 'Y' ){
					$sql         = $baseSql . " AND se.rsvpStatus = 'PlusOne'" . $rsvp_event_where;
					$yesResults += (int) $wpdb->get_var( $wpdb->prepare( $sql, $eventID, $eventID ) );
				}
			}

		}

		if ( isset( $_GET['event_list'] ) && '' != $_GET['event_list'] ){
			$class = $_GET['event_list'];
		} else {
			$class = 'all';
		}

		return array(
				'all'               => '<a href="' . admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $eventID ) . '" class="' . ( ( 'all' == $class ) ? 'current' : '' ) . '">All  <span class="count">(' . $all . ')</span></a>',
				'yes_count'         => '<a href="' . admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $eventID ) . '&search_field=rsvpStatus&s=Yes&event_list=yes_count" class="' . ( ( 'yes_count' == $class ) ? 'current' : '' ) . '">Yes  <span class="count">(' . $yesResults . ')</a>',
				'no_count'          => '<a href="' . admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $eventID ) . '&search_field=rsvpStatus&s=No&event_list=no_count" class="' . ( ( 'no_count' == $class ) ? 'current' : '' ) . '">No  <span class="count">(' . $noResults . ')</span></a>',
				'no_response_count' => '<a href="' . admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $eventID ) . '&search_field=rsvpStatus&s=NoResponse&event_list=no_response_count" class="' . ( ( 'no_response_count' == $class ) ? 'current' : '' ) . '">No response <span class="count">(' . $noResponseResults . ')</span></a>',
		);
	}
}
