<?php
/**
 * Logs list Template
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Templates\Admin\Logs;


use DDWCPointsAndRewards\Helper\Log\DDWCPR_Log_Helper;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Logs_List_Template' ) ) {
	/**
	 * Logs list class
	 */
	class DDWCPR_Logs_List_Template extends \WP_List_table {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Log Helper Variable
		 *
		 * @var object
		 */
		protected $log_helper;

		/**
		 * Args Variable
		 *
		 * @var array
		 */
		protected $args;

		/**
		 * Construct
		 * 
		 * @param array $ddwcpr_configuration
		 */
		public function __construct( $ddwcpr_configuration ) {
			$this->ddwcpr_configuration = $ddwcpr_configuration;
			$this->log_helper           = new DDWCPR_Log_Helper( $ddwcpr_configuration );

			parent::__construct( [
				'singular' => esc_html__( 'Log List', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'plural'   => esc_html__( 'Logs List', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'ajax'     => false,
			] );
		}

		/**
		 * Prepare Items
		 *
		 * @return void
		 */
		public function prepare_items() {
			$this->_column_headers = $this->get_column_info();

			$request_scheme = is_ssl() ? 'https' : 'http';
			$current_url    = "$request_scheme://" . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) . sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

			if ( strpos( $current_url, '_wp_http_referer' ) !== false ) {
				$new_url = remove_query_arg( [ '_wp_http_referer', '_wpnonce' ], stripslashes( $current_url ) );
				wp_safe_redirect( $new_url );
				exit();
			}

			$this->process_bulk_action();
			$this->process_row_action();

			$search       = ! empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
			$per_page     = $this->get_items_per_page( 'ddwcpr_logs_per_page', 20 );
			$current_page = $this->get_pagenum();
			$offset       = ( $current_page - 1 ) * $per_page;

			$this->args = [
				'search'    => ! empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '',
				'event'     => ! empty( $_GET['event'] ) ? sanitize_text_field( wp_unslash( $_GET['event'] ) ) : '',
				'user_id'   => ! empty( $_GET['user-id'] ) ? sanitize_text_field( wp_unslash( $_GET['user-id'] ) ) : '',
				'from_date' => ! empty( $_GET['from-date'] ) ? sanitize_text_field( wp_unslash( $_GET['from-date'] ) ) : '',
				'end_date'  => ! empty( $_GET['end-date'] ) ? sanitize_text_field( wp_unslash ( $_GET['end-date'] ) ) : '',
				'per_page'  => $per_page,
				'offset'    => $offset,
			];

			$results     = $this->log_helper->ddwcpr_get_logs( $this->args );
			$total_items = $this->log_helper->ddwcpr_get_logs_count( $this->args );

			$this->set_pagination_args( [
				'total_items' => $total_items,
				'per_page'    => $per_page,
			] );

			$data = $this->ddwcpr_prepare_data( $results );

			usort( $data, [ $this, 'usort_reorder' ] );

			$this->items = $data;
		}

		/**
		 * Usort
		 *
		 * @param int $first First value.
		 * @param int $second Second value.
		 * @return $result
		 */
		public function usort_reorder( $first, $second ) {
			$orderby = ! empty( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : 'id';
			$order   = ! empty( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : 'desc';
			$result  = strnatcmp( $first[ $orderby ], $second[ $orderby ] );

			return 'asc' === $order ? $result : -$result;
		}

		/**
		 * Fetch Data function
		 *
		 * @param array $results
		 * @return array $data
		 */
		public function ddwcpr_prepare_data( $results ) {
			$data = [];

			if ( ! empty( $results ) ) {
				foreach ( $results as $result ) {
					$result_id       = $result['id'];
					$user_id         = $result['user_id'];
					$related_id      = $result['related_id'];
					$result_event    = $result['event'];
					$user            = get_userdata( $user_id );

					if ( ! empty( $user ) && is_object( $user ) ) {
						$related_id_html = '-';

						if ( ! empty( $related_id ) ) {
							if ( 'review_submission' === $result_event ) {
								$product = wc_get_product( $related_id );

								if ( $product ) {
									$related_id_html = sprintf( esc_html__( 'Product: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href=' . esc_url( $product->get_permalink() ) . ' target="_blank">' . esc_html( $product->get_name() ) . '</a>' );
								}
							} else {
								$order = wc_get_order( $related_id );
								if ( $order ) {
									$related_id_html = sprintf( esc_html__( 'Order: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href=' . esc_url( admin_url( 'admin.php?page=wc-orders&action=edit&id=' . $related_id ) ) . ' target="_blank">#' . esc_html( $order->get_order_number() ) . '</a>' );
								} else {
									// For Coupon
									$coupon = new \WC_Coupon( $related_id );
									if ( $coupon->get_id() ) {
										$edit_url = admin_url( 'post.php?post=' . $coupon->get_id() . '&action=edit' );
										$related_id_html = sprintf( esc_html__( 'Coupon: %s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<a href="' . esc_url( $edit_url ) . '" target="_blank">' . esc_html( strtoupper( $coupon->get_code() ) ) . '</a>' );
									}
								}
							}
						}

						ob_start();
						if ( $result['points'] > 0 ) {
							?>
							<span class="ddwcpr-added">+<?php echo esc_html( $result['points'] ); ?></span>
							<?php
						} else if ( $result['points'] < 0 ) {
							?>
							<span class="ddwcpr-deducted"><?php echo esc_html( $result['points'] ); ?></span>
							<?php
						} else {
							?>
							<span class="ddwcpr-normal"><?php echo esc_html( $result['points'] ); ?></span>
							<?php
						}
						$points_html = ob_get_clean();

						$email = $user->user_email . ' (#' . $user_id . ')';
						$data[] = apply_filters( 'ddwcpr_modify_log_row_data', [
							'id'          => $result_id,
							'event'       => ddwcpr_get_translation( $result_event ),
							'user'        => '<a href=' . esc_url( admin_url( 'user-edit.php?user_id=' . $user_id ) ) . '>' . esc_html( $email ) . '</a>',
							'related_id'  => $related_id_html,
							'points'      => $points_html,
							'date'        => date_i18n( 'F d, Y g:i:s A', strtotime( $result['date'] ) ),
							'description' => $result['description'],
						], $result );
					}
				}
			}

			return apply_filters( 'ddwcpr_logs_list_data', $data );
		}

		/**
		 *  No items
		 *
		 * @return void
		 */
		public function no_items() {
			esc_html_e( 'No logs avaliable.', 'loyaltyx-points-and-rewards-for-woocommerce' );
		}

		/**
		 * Hidden Columns
		 *
		 * @return array
		 */
		public function get_hidden_columns() {
			return [];
		}

		/**
		 *  Associative array of columns
		 *
		 * @return array
		 */
		public function get_columns() {
			$columns = [
				'id'          => esc_html__( 'ID', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'user'        => esc_html__( 'User', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'points'      => esc_html__( 'Points', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'event'       => esc_html__( 'Event', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'description' => esc_html__( 'Description', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'related_id'  => esc_html__( 'Related ID', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'date'        => esc_html__( 'Date', 'loyaltyx-points-and-rewards-for-woocommerce' ),
			];

			return apply_filters( 'ddwcpr_logs_list_columns', $columns );
		}

		/**
		 * Columns to make sortable.
		 *
		 * @return array
		 */
		public function get_sortable_columns() {
			return apply_filters( 'ddwcpr_logs_list_sortable_columns', [
				'id'     => [ 'id', true ],
				'event'  => [ 'event', true ],
				'points' => [ 'points', true ],
				'date'   => [ 'date', true ],
			] );
		}

		/**
		 * Render a column when no column specific method exists.
		 *
		 * @param array  $item Items.
		 * @param string $column_name Name.
		 *
		 * @return mixed
		 */
		public function column_default( $item, $column_name ) {
			return array_key_exists( $column_name, $item ) ? $item[ $column_name ] : print_r( $item, true );
		}

		/**
		 * Filters function
		 *
		 * @param string $which Position of filter.
		 */
		public function extra_tablenav( $which ) {
			if ( 'top' === $which ) {
				$events = [
					'manual_adjustment'   => esc_html__( 'Manual Adjustment by Admin', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'order_completion'    => esc_html__( 'Order Completion', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'order_refunded'      => esc_html__( 'Order Refunded', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'order_cancelled'     => esc_html__( 'Order Cancelled', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'order_failed'        => esc_html__( 'Order Failed', 'loyaltyx-points-and-rewards-for-woocommerce' ),
					'points_conversion'   => esc_html__( 'Points Conversion Reward', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				];
				?>
				<div class="alignleft actions bulkactions">
					<select name="event" class="regular-text">
						<option value=""><?php esc_html_e( 'All Events', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></option>

						<?php
						foreach ( $events as $event_value => $event_html ) {
							?>
							<option value="<?php echo esc_attr( $event_value ); ?>" <?php echo esc_attr( $event_value === $this->args['event'] ? 'selected="selected"' : '' ); ?>><?php echo esc_attr( $event_html ); ?></option>
							<?php
						}
						?>
					</select>

					<label for="from-date">&nbsp;<?php esc_html_e( 'From:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label>
					<input type="date" value="<?php echo esc_attr( $this->args['from_date'] ); ?>" name="from-date" id="from-date" class="ddwcpr-datepicker" placeholder="yyyy-mm-dd" autocomplete="off" />

					<label for="end-date">&nbsp;<?php esc_html_e( 'To:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></label>
					<input type="date" value="<?php echo esc_attr( $this->args['end_date'] ); ?>" name="end-date" id="end-date" class="ddwcpr-datepicker" placeholder="yyyy-mm-dd" autocomplete="off" />

					<select name="user-id" id="ddwcpr-users" class="regular-text ddfw-users" data-placeholder="<?php esc_attr_e( 'Select User', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>">
						<?php
						if ( ! empty( $this->args['user_id'] ) ) {
							$user_data = get_userdata( $this->args['user_id'] );
							?>
							<option value="<?php echo esc_attr( $this->args['user_id'] ); ?>"><?php echo esc_html( "(#{$this->args['user_id']}) {$user_data->user_login} <{$user_data->user_email}>" ); ?></option>
							<?php
						}
						?>
					</select>

					<input type="submit" value="<?php esc_attr_e( 'Filter', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?>" name="ddwcpr_filter_submit" class="button" />

					<?php
					if ( ! empty( $_GET['ddwcpr_filter_submit'] ) ) {
						$page = ! empty( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
						$menu = ! empty( $_GET['menu'] ) ? sanitize_text_field( wp_unslash( $_GET['menu'] ) ) : '';
						?>
						<a href="<?php echo esc_url( admin_url( "admin.php?page={$page}&menu={$menu}" ) ); ?>" name="ddwcpr_filter_reset" class="button"><?php esc_html_e( 'Reset', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></a>
						<?php
					}
					?>
				</div>
				<?php
			}
		}
	}
}
