<?php
/**
 * RSVP Events  list table
 *
 * @version 4.4.8
 */

class RSVP_PRO_Events_List_Table extends RSVP_PRO_List_Table {

	public function __construct( $args = array() ){
		parent::__construct( array(
				'plural'   => 'events',
				'singular' => 'event',
				'ajax'     => false,
				'screen'   => null,
		) );
	}

	/**
	 * Message to be displayed when there are no items
	 *
	 * @since  4.4.8
	 * @access public
	 */
	public function no_items(){
		echo __( 'No events found. ', 'rsvp-pro-plugin' ) . '<a href="' . admin_url( 'admin.php?page=rsvp-pro-admin-manage-event' ) . '">' . __( 'Create one now', 'rsvp-pro-plugin' ) . '</a>';
	}

	public function prepare_items(){
		global $wpdb;

		$sql = 'SELECT id, eventName, open_date, close_date, options, parentEventID, event_access, eventStartDate, eventEndDate, eventLocation, eventDescription,repeatStartDate, repeatEndDate, repeatFrequencyType, eventLength, eventLengthType, currentRepeatEndDate, open_date_timezone, open_date_time, close_date_timezone, close_date_time, attendee_list_sent_on, send_attendee_list, attendee_columns, eventStartDateTimezone, eventEndDateTimezone FROM ' . PRO_EVENT_TABLE .
			   ' WHERE id != ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;

		if ( $_GET && isset( $_GET['s'] ) && '' != $_GET['s'] ){
			$sql .= ' AND eventName LIKE \'%' . esc_html( $_GET['s'] ) . '%\'';
		}

		$data     = $wpdb->get_results( $sql );
		$columns  = $this->get_columns();
		$hidden   = $this->get_hidden_columns();
		$sortable = $this->get_sortable_columns();

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

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

		$this->items = $this->prepare_events( $data );
	}

	public function get_columns(){
		$columns = array(
			'cb'         => 'cb',
			'eventId'    => __( 'Event ID', 'rsvp-pro-plugin' ),
			'event_name' => __( 'Event Name', 'rsvp-pro-plugin' ),
			'shortcode'  => __( 'shortcode', 'rsvp-pro-plugin' ),
			'attendees'  => __( 'Attendees', 'rsvp-pro-plugin' ),
		);

		return $columns;
	}

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

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


	/**
	 * @param $item
	 * @param $column_name
	 *
	 * @return mixed|void
	 * @since 4.4.8
	 */
	public function column_default( $item, $column_name ){

		switch ( $column_name ){

			case 'eventId':
				$text = esc_html( $item['id'] );
				break;
			case 'event_name':
				$text = esc_html( $item[ $column_name ] );
				break;
			default:
				$text = esc_html( $item[ $column_name ] );
		}

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

	/**
	 * @param int $level
	 *
	 * @param     $item
	 *
	 * @since 4.4.8
	 */
	public function single_row( $item, $level = 0 ){

		$classes = '';
		if ( isset( $item['parent_id'] ) && '0' != $item['parent_id'] ){
			$classes = 'level-1';
		} else {
			$classes = 'level-0';
		}
		?>
		<tr id="event-<?php echo $item['id']; ?>" class="<?php echo esc_attr( $classes ); ?>">
			<?php $this->single_row_columns( $item ); ?>
		</tr>
		<?php
	}


	/**
	 * Display the table
	 *
	 * @since  4.4.8
	 * @access public
	 */
	public function display(){

		$this->prepare_items();

		$singular = $this->_args['singular'];
		?>
		<form id="posts-filter" method="get">
			<p class="search-box">
				<label class="screen-reader-text"
					   for="post-search-input"><?php esc_html_e( 'Search', 'rsvp-pro-plugin' ); ?></label>
				<input type="hidden" name="page" value="rsvp-pro-top-level">
				<input type="search" id="post-search-input" name="s"
					   value="<?php echo( isset( $_GET['s'] ) && !empty( $_GET['s'] ) ? $_GET['s'] : '' ) ?>">
				<input type="submit" id="search-submit" class="button"
					   value="<?php esc_html_e( 'Search event', 'rsvp-pro-plugin' ); ?>">

			</p>
			<?php
			$this->display_tablenav( 'top' );

			if ( 'Y' === get_option( RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST ) ) :
				?>
				<table class="widefat post fixed striped">
					<tbody>
					<tr class="format-standard hentry category-uncategorized iedit author-self">
						<td class="post-title column-title page-title">
							<strong><?php echo rsvp_pro_get_admin_string( 'global_attendee_list' ); ?></strong>
							<div>
							<span class="import"><a
										href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=import&eventID=' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ); ?>">
																	 <?php
																	 echo rsvp_pro_get_admin_string( 'import_attendees_label' );
																	 ?>
							</a> | </span>
								<span class="create_attendee"><a
											href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=modify_attendee&eventID=' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ); ?>">
																			  <?php
																			  echo rsvp_pro_get_admin_string( 'add_attendees_button' );
																			  ?>
							</a></span>
							</div>
						</td>
						<td>
							<a href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ); ?>"
							   title="Manage Attendees"><?php echo rsvp_pro_get_admin_string( 'manage_attendees_label' ); ?></a>
						</td>
					</tr>
					</tbody>
				</table>
				<p><br/></p>
			<?php endif; // Check for if the Global attendee list is enabled.
			?>
			<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 $events
	 *
	 * @return mixed
	 * @since 4.4.8
	 */
	function prepare_events( $events ){

		$return = array();
		foreach ( $events as $event ){

			$return[ $event->id ] = array(
					'id'                        => $event->id,
					'event_name'                => $event->eventName,
					'parent_id'                 => $event->parentEventID,
					'open_date'                 => $event->open_date,
					'close_date'                => $event->close_date,
					'options'                   => $event->options,
					'event_access'              => $event->event_access,
					'event_start_date'          => $event->eventStartDate,
					'event_end_date'            => $event->eventEndDate,
					'event_location'            => $event->eventLocation,
					'event_description'         => $event->eventDescription,
					'repeat_start_date'         => $event->repeatStartDate,
					'repeat_end_date'           => $event->repeatEndDate,
					'repeat_frequency_type'     => $event->repeatFrequencyType,
					'repeat_frequency'          => (isset($event->repeatFrequency)) ? $event->repeatFrequency : false,
					'event_length'              => $event->eventLength,
					'event_length_type'         => $event->eventLengthType,
					'current_repeat_end_date'   => $event->currentRepeatEndDate,
					'open_date_timzezone'       => $event->open_date_timezone,
					'open_date_time'            => $event->open_date_time,
					'close_date_timezone'       => $event->close_date_timezone,
					'close_date_time'           => $event->close_date_time,
					'attendee_list_sent_on'     => $event->attendee_list_sent_on,
					'send_attendee_list'        => $event->send_attendee_list,
					'attendee_columns'          => $event->attendee_columns,
					'event_start_date_timezone' => $event->eventStartDateTimezone,
					'event_end_date_timezone'   => $event->eventEndDateTimezone
			);
		}

		return $return;

	}

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

	}

	/**
	 * The Shortcode column output
	 *
	 * @param $item
	 *
	 * @since 4.4.8
	 */
	public function column_shortcode( $item ){
		?>
		[rsvppro id="<?php echo absint( $item['id'] ); ?>"]<br/>
		[rsvppro-attendeelist id=&quot;<?php echo absint( $item['id'] ); ?>&quot;]
		<?php do_action( 'rsvp_pro_event_list_shortcodes', $item );
	}

	/**
	 * The Attendees column output
	 *
	 * @param $item
	 *
	 * @since 4.4.8
	 */
	public function column_attendees( $item ){
		$url = add_query_arg( array(
				'page'    => 'rsvp-pro-top-level',
				'action'  => 'attendees',
				'eventID' => absint( $item['id'] )
		), admin_url( 'admin.php' ) );
		?>
		<a href="<?php echo esc_url( $url ); ?>"
		   title="Manage Attendees"><?php echo rsvp_pro_get_admin_string( 'manage_attendees_label' ); ?></a>
		<?php

		$links = array(
				'export_attendees'    => array(
						'placeholder' => esc_html__( 'Export Attendees', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'export_attendee_form',
								'eventID' => absint( $item['id'] ),
						),
				),
				'import_attendees'    => array(
						'placeholder' => esc_html__( 'Import Attendees', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'import',
								'eventID' => absint( $item['id'] ),
						),
				),
				'import_from_free'    => array(
						'placeholder' => esc_html__( 'Import attendees and custom questions from Free RSVP', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'import_from_free',
								'eventID' => absint( $item['id'] ),
						),
				),
				'mass_mail'           => array(
						'placeholder' => esc_html__( 'Send Message', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'mass_email',
								'eventID' => absint( $item['id'] ),
						),
				),
				'reset_all_attendees' => array(
						'placeholder' => esc_html__( 'Reset All Attendees', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'confirm_reset_all_attendees',
								'eventID' => absint( $item['id'] ),
						),
				)
		);
		global $wpdb;
		$sql           = 'SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d';
		$parentEventID = $wpdb->get_var( $wpdb->prepare( $sql, $item['id'] ) );

		if ( $parentEventID > 0){
			$links['export_attendees_sub'] = array(
					'placeholder' => esc_html__( 'Export Attendees w/Sub-Event Information', 'rsvp-pro-plugin' ),
					'url_vals'    => array(
							'page'        => 'rsvp-pro-top-level',
							'action'      => 'export',
							'includeSubs' => 'true',
							'eventID'     => absint( $item['id'] ),
					),
			);
		}

		$actions = array();

		// If user doesn't have access to event don't allor it
		if ( !rsvp_pro_admin_user_has_access_to_settings( $item['id'] ) ){
			$actions = apply_filters( 'rsvp_attendees_actions', $actions, $item );
			echo ( ( isset( $item['parent_id'] ) && '0' != $item['parent_id'] ) ? '&#8212; ' : '' ) . esc_html( $item['event_name'] );
			echo $this->row_actions( $actions );

			return;
		}

		if ( !rsvp_pro_is_free_rsvp_installed() ){
			unset( $links['import_from_free'] );
		}

		foreach ( $links as $key => $link ){
			$url             = add_query_arg( $link['url_vals'], admin_url( 'admin.php' ) );
			$actions[ $key ] = "<a href='" . esc_url( $url ) . "' >" . esc_html( $link['placeholder'] ) . '</a>';
		}


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

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

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

		// Edit link
		$edit_link = add_query_arg( array(
				'page' => 'rsvp-pro-admin-manage-event',
				'id'   => $item['id']
		), admin_url( 'admin.php' ) );

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

		$links = array(
				'custom_questions' => array(
						'placeholder' => esc_html__( 'Custom Questions', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'custom_questions',
								'eventID' => absint( $item['id'] ),
						),
				),
				'copy_event'       => array(
						'placeholder' => esc_html__( 'Clone Event', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'copy',
								'eventID' => absint( $item['id'] ),
						),
				),
				'message_logs'     => array(
						'placeholder' => esc_html__( 'Message Logs', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'message_logs',
								'eventID' => absint( $item['id'] ),
						),
				),
				'reminders'        => array(
						'placeholder' => esc_html__( 'Reminders', 'rsvp-pro-plugin' ),
						'url_vals'    => array(
								'page'    => 'rsvp-pro-top-level',
								'action'  => 'reminders',
								'eventID' => absint( $item['id'] ),
						),
				),
		);


		$actions = array();

		// If user doesn't have access to event don't allor it
		if ( !rsvp_pro_admin_user_has_access_to_settings( $item['id'] ) ){
			$actions = apply_filters( 'rsvp_attendees_actions', $actions, $item );
			echo ( ( isset( $item['parent_id'] ) && '0' != $item['parent_id'] ) ? '&#8212; ' : '' ) . esc_html( $item['event_name'] );
			echo $this->row_actions( $actions );

			return;
		}

		echo '<a class="row-title" href="' . $edit_link . '">' . ( ( isset( $item['parent_id'] ) && '0' != $item['parent_id'] ) ? '&#8212; ' : '' ) . esc_html( $item['event_name'] ) . '</a>';
		// Assemble links
		$actions['edit']   = '<a href="' . $edit_link . '">' . __( 'Edit', 'rsvp-pro-plugin' ) . '</a>';
		$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( $delete_link, 'rsvp-pro-top-level' ) . "' >" . __( 'Delete', 'rsvp-pro-plugin' ) . '</a>';

		if ( !rsvp_pro_is_free_rsvp_installed() ){
			unset( $links['import_from_free'] );
		}

		foreach ( $links as $key => $link ){
			$url             = add_query_arg( $link['url_vals'], admin_url( 'admin.php' ) );
			$actions[ $key ] = "<a href='" . esc_url( $url ) . "' >" . esc_html( $link['placeholder'] ) . '</a>';
		}


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

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

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

		$actions = array(
				'delete_events'   => __( 'Delete events', 'rsvp-pro-plugin' ),
				'delete_events_and_attendees' => __( 'Delete events and their attendees', 'rsvp-pro-plugin' )
		);

		return $actions;
	}

}
