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

namespace DDWCPointsAndRewards\Templates\Admin\Points_Rules\Points_Redeeming;

use DDWCPointsAndRewards\Helper\Rule\DDWCPR_Rule_Helper;

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

if ( ! class_exists( 'DDWCPR_Points_Redeeming_Rules_List_Template' ) ) {
	/**
	 * Points redeeming rules list class
	 */
	class DDWCPR_Points_Redeeming_Rules_List_Template extends \WP_List_table {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Rule Helper Variable
		 *
		 * @var object
		 */
		protected $rule_helper;

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

			parent::__construct( [
				'singular' => esc_html__( 'Rule List', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'plural'   => esc_html__( 'Rules 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_points_rules_per_page', 20 );
			$current_page = $this->get_pagenum();
			$offset       = ( $current_page - 1 ) * $per_page;

			$args = [
				'search'    => ! empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '',
				'per_page'  => $per_page,
				'offset'    => $offset,
			];

			$results     = $this->rule_helper->ddwcpr_get_redeeming_rules( $args );
			$total_items = $this->rule_helper->ddwcpr_get_redeeming_rules_count( $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 $key => $result ) {
					ob_start();
					?>
					<mark class="ddwcpr-status ddwcpr-status-<?php echo esc_attr( $result['status'] ); ?>"><?php echo esc_html( ddwcpr_get_translation( $result['status'] ) ); ?></mark>
					<?php
					$status_html = ob_get_clean();

					$data[] = apply_filters( 'ddwcpr_modify_redeeming_rule_row_data', [
						'id'         => $result['id'],
						'name'       => $result['name'],
						'priority'   => $result['priority'],
						'type'       => ddwcpr_get_translation( $result['type'] ),
						'start_date' => $result['start_date'] ? date_i18n( 'F d, Y', strtotime( $result['start_date'] ) ) : '-',
						'end_date'   => $result['end_date'] ? date_i18n( 'F d, Y', strtotime( $result['end_date'] ) ) : '-',
						'status'     => $status_html,
					], $result );
				}
			}

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

		/**
		 * Process bulk actions
		 *
		 * @return void
		 */
		public function process_bulk_action() {
			if ( ! empty( $_GET['ddwcpr_nonce'] ) ) {
				if ( wp_verify_nonce( sanitize_text_field( wp_unslash ( $_GET['ddwcpr_nonce'] ) ), 'ddwcpr_nonce_action' ) ) {
					$action = $this->current_action();

					if ( in_array( $action, [ 'active', 'inactive', 'delete' ] ) ) {
						if ( isset( $_GET['ddwcpr-id'] ) ) { // WPCS: input var ok.
							if ( is_array( $_GET['ddwcpr-id'] ) ) { // WPCS: input var ok.
								$ids = array_map( 'sanitize_text_field', wp_unslash( $_GET['ddwcpr-id'] ) ); // WPCS: input var ok.

								$success = $error = 0;

								foreach ( $ids as $id ) {
									if ( 'delete' === $action ) {
										$response = $this->rule_helper->ddwcpr_delete_redeeming_rule( $id );
									} else {
										$this->rule_helper->ddwcpr_update_redeeming_rule_status( $id, $action );
										$response = true;
									}

									if ( $response ) {
										$success++;
									} else {
										$error++;
									}
								}

								if ( $success ) {
									if ( 'delete' === $action ) {
										$message = sprintf( esc_html__( '%d rule(s) deleted successfully.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $success );
									} else {
										$message = sprintf( esc_html__( 'Status changed for %d rule(s) successfully.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $success );
									}

									ddfw_print_notification( $message );
								}

								if ( $error ) {
									$message = sprintf( esc_html__( '%d rule(s) not exists.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $error );
									ddfw_print_notification( $message, 'error' );
								}
							}
						} else {
							$message = esc_html__( 'Select rule(s) first.', 'loyaltyx-points-and-rewards-for-woocommerce' );
							ddfw_print_notification( $message, 'error' );
						}
					}
				} else {
					$message = esc_html__( 'Invalid nonce. Security check failed!!!', 'loyaltyx-points-and-rewards-for-woocommerce' );
					ddfw_print_notification( $message, 'error' );
				}
			}
		}

		/**
		 * Process row actions
		 *
		 * @return void
		 */
		public function process_row_action() {
			if ( ! empty( $_GET['ddwcpr_nonce'] ) ) {
				if ( wp_verify_nonce( sanitize_text_field( wp_unslash ( $_GET['ddwcpr_nonce'] ) ), 'ddwcpr_nonce_action' ) ) {
					$action = $this->current_action();

					if ( in_array( $action, [ 'delete' ] ) ) {
						if ( isset( $_GET['ddwcpr-id'] ) && ! is_array( $_GET['ddwcpr-id'] ) ) { // WPCS: input var ok.
							$id       = intval( wp_unslash( $_GET['ddwcpr-id'] ) );  // WPCS: input var ok.
							$response = $this->rule_helper->ddwcpr_delete_redeeming_rule( $id );

							if ( $response ) {
								$message = esc_html__( 'Rule is deleted successfully.', 'loyaltyx-points-and-rewards-for-woocommerce' );
								ddfw_print_notification( $message );
							} else {
								$message = esc_html__( 'Rule not exists.', 'loyaltyx-points-and-rewards-for-woocommerce' );
								ddfw_print_notification( $message, 'error' );
							}
						}
					}
				} else {
					$message = esc_html__( 'Invalid nonce. Security check failed!!!', 'loyaltyx-points-and-rewards-for-woocommerce' );
					ddfw_print_notification( $message, 'error' );
				}
			}
		}

		/**
		 *  No items
		 *
		 * @return void
		 */
		public function no_items() {
			esc_html_e( 'No rules 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 = [
				'cb'         => '<input type="checkbox" />',
				'name'       => esc_html__( 'Name', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'type'       => esc_html__( 'Type', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'priority'   => esc_html__( 'Priority', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'start_date' => esc_html__( 'Start Date', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'end_date'   => esc_html__( 'End Date', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'status'     => esc_html__( 'Status', 'loyaltyx-points-and-rewards-for-woocommerce' ),
			];

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

		/**
		 * Columns to make sortable.
		 *
		 * @return array
		 */
		public function get_sortable_columns() {
			return apply_filters( 'ddwcpr_redeeming_rules_list_sortable_columns', [
				'id'         => [ 'id', true ],
				'name'       => [ 'name', true ],
				'start_date' => [ 'start_date', true ],
				'end_date'   => [ 'end_date', true ],
				'status'     => [ 'status', 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 );
		}

		/**
		 * Render the bulk edit checkbox
		 *
		 * @param array $item Item.
		 * @return string
		 */
		public function column_cb( $item ) {
			return sprintf( '<input type="checkbox" name="ddwcpr-id[]" value="%d" />', esc_attr( $item['id'] ) );
		}

		/**
		 * Column actions
		 *
		 * @param array $item Items.
		 * @return array $actions
		 */
		public function column_name( $item ) {
			$page         = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
			$menu         = isset( $_GET['menu'] ) ? sanitize_text_field( wp_unslash( $_GET['menu'] ) ) : '';
			$search       = ! empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
			$current_page = $this->get_pagenum();

			$actions = [
				'edit'   => sprintf( '<a href="%s">%s</a>', esc_url( admin_url( "admin.php?page={$page}&menu={$menu}&tab={$_GET['tab']}&action=edit&ddwcpr-id={$item['id']}" ) ), esc_html__( 'Edit', 'loyaltyx-points-and-rewards-for-woocommerce' ) ),
				'delete' => sprintf( '<a href="%s">%s</a>', wp_nonce_url( "admin.php?page={$page}&menu={$menu}&tab={$_GET['tab']}&action=delete&s={$search}&paged={$current_page}&ddwcpr-id={$item['id']}", 'ddwcpr_nonce_action', 'ddwcpr_nonce' ), esc_html__( 'Delete', 'loyaltyx-points-and-rewards-for-woocommerce' ) ),
			];

			return sprintf( '%1$s %2$s', $item['name'], $this->row_actions( apply_filters( 'ddwcpr_redeeming_rules_list_line_actions', $actions ) ) );
		}

		/**
		 * Bulk actions on list.
		 * 
		 * @return array
		 */
		public function get_bulk_actions() {
			return apply_filters( 'ddwcpr_modify_bulk_actions_in_redeeming_rules_list', [
				'active'   => esc_html__( 'Set Active', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'inactive' => esc_html__( 'Set Inactive', 'loyaltyx-points-and-rewards-for-woocommerce' ),
				'delete'   => esc_html__( 'Delete', 'loyaltyx-points-and-rewards-for-woocommerce' ),
			] );
		}
	}
}
