<?php

namespace Discountify\Core\Admin\Settings;

defined( 'ABSPATH' ) || exit;

use Discountify\Utils\Helper;

if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/inclueds/class-wp-list-table.php';
}

class Table extends \WP_List_Table {

	public $singular_name;
	public $plural_name;
	public $id      = '';
	public $columns = array();

	/**
	 * Show list
	 */
	function __construct( $all_data_of_table ) {

		$this->singular_name = $all_data_of_table['singular_name'];
		$this->plural_name   = $all_data_of_table['plural_name'];
		$this->columns       = $all_data_of_table['columns'];

		parent::__construct(
			array(
				'singular' => $this->singular_name,
				'plural'   => $this->plural_name,
				'ajax'     => true,
			)
		);
	}

	protected function column_discount_name( $item ) {
		$_wpnonce = esc_attr( wp_create_nonce( 'delete-rules-nonce' ) );
		$actions  = array(
			'delete' => sprintf(
				'<a href="?page=%s&action=%s&id=%s&_wpnonce=%s" aria-label="%s" role="button">%s</a>',
				'discountify-rules',
				'delete',
				$item['ID'],
				$_wpnonce,
				__( 'Delete', 'discountify' ),
				__( 'Delete', 'discountify' )
			),
			'edit'   => sprintf(
				'<a href="?page=%s&rule=%s&id=%s" aria-label="%s" role="button">%s</a>',
				'discountify-rules',
				'update-rule',
				$item['ID'],
				__( 'Edit', 'discountify' ),
				__( 'Edit', 'discountify' )
			),
		);

		return $item['discount_name'] . $this->row_actions( $actions );
	}

	/**
	 * Get column header function
	 */
	public function get_columns() {
		return $this->columns;
	}

	public function extra_tablenav( $which ) {
		$rules  = Helper::instance()->rules_type( true );
		$submit = array( 'id' => 'filter-by-rules' );

		?>
		<div class="alignleft actions bulkactions">
			<input type="hidden" name="discount_rules" class="discount_rules" value=""/>
			<select name="rules_type" class="filter_rules_type">
				<?php
				if ( count( $rules ) > 0 ) {
					// phpcs:ignore WordPress.Security.NonceVerification.Missing -- This is a filter display, nonce checked in process_bulk_action
					$discount_rules = ! empty( $_POST['discount_rules'] ) ? sanitize_text_field( wp_unslash( $_POST['discount_rules'] ) ) : '';
					?>
						<option value=""><?php esc_html_e( 'Select Discount Rules', 'discountify' ); ?></option>
					<?php
					foreach ( $rules as $key => $value ) {
						$selected = $discount_rules === $key ? 'selected' : '';

						?>
							<option  <?php echo esc_attr( $selected ); ?> value="<?php echo esc_html( $key ); ?>"><?php echo esc_html( $value ); ?></option>
						<?php
					}
				} else {
					?>
						<option value=""><?php esc_html_e( 'No rules found', 'discountify' ); ?></option>
						<?php
				}

				?>
			</select>
		</div>
		<?php
		submit_button( esc_html__( 'Filter By Rules', 'discountify' ), '', 'filter-by-rules', false, $submit );
	}

	/**
	 * Render the bulk edit checkbox
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="bulk-delete[]" value="%1$s" />',
			$item['ID']
		);
	}

	/**
	 * Delete data
	 */
	public function process_bulk_action() {
		$action = $this->current_action();
		if ( 'delete' === $action &&
		isset( $_GET['_wpnonce'] ) && ! empty( $_GET['_wpnonce'] ) ) {
			$nonce = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_SPECIAL_CHARS );
			if ( ! wp_verify_nonce( $nonce, 'delete-rules-nonce' ) ) {
				wp_die( esc_html__( 'Security check failed!', 'discountify' ) );
			}
			$id = isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0;
			if ( $id > 0 ) {
				wp_delete_post( $id, true );
			}
		}
		if ( 'trash' === $action && isset( $_POST['bulk-delete'] ) ) {
			$delete_ids = array_unique( array_map( 'absint', $_POST['bulk-delete'] ) );
			foreach ( $delete_ids as $did ) {
				wp_delete_post( $did, true );
			}
			wp_safe_redirect( esc_url( add_query_arg() ) );

			exit;
		}
	}

	/**
	 * Get Bulk options
	 */
	public function get_bulk_actions() {
		$actions          = array();
		$actions['trash'] = esc_html__( 'Move to Trash', 'discountify' );

		return $actions;
	}

	/**
	 * Sortable column function
	 */
	public function get_sortable_columns() {
		unset( $this->columns['cb'] );
		unset( $this->columns['enable_rules'] );

		return $this->columns;
	}

	/**
	 * Display all row function
	 */
	protected function column_default( $item, $column_name ) {
		switch ( $column_name ) {
			case 'discount_in':
				$discount_name = '';
				if ( $item[ $column_name ] === 'product' && ! empty( $item['filter_by_products'] ) ) {
					// Check if "all" is selected
					if ( $item['filter_by_products'] === 'all' || ( is_array( $item['filter_by_products'] ) && in_array( 'all', $item['filter_by_products'], true ) ) ) {
						$discount_name = '<strong>' . esc_html__( 'Products:', 'discountify' ) . '</strong>' . ' ' . esc_html__( 'All', 'discountify' );
					} else {
						$discount_name = '<strong>' . esc_html__( 'Products:', 'discountify' ) . '</strong>' . ' ' . $this->get_discount_in( $item['filter_by_products'] );
					}
				} elseif ( $item[ $column_name ] === 'category' && ! empty( $item['filter_by_category'] ) ) {
					// Check if "all" is selected
					if ( $item['filter_by_category'] === 'all' || ( is_array( $item['filter_by_category'] ) && in_array( 'all', $item['filter_by_category'], true ) ) ) {
						$discount_name = '<strong>' . esc_html__( 'Categories:', 'discountify' ) . '</strong>' . ' ' . esc_html__( 'All', 'discountify' );
					} else {
						$discount_name = '<strong>' . esc_html__( 'Categories:', 'discountify' ) . '</strong>' . ' ' . $this->get_discount_in( $item['filter_by_category'], 'category' );
					}
				}

				return $discount_name;

			case 'enable_rules':
				$checked = $item[ $column_name ] === 'yes' ? 'checked' : '';
				$nonce   = wp_create_nonce( 'discountify_toggle_rule_' . $item['ID'] );
				return '<div style="text-align:center;">
					<label class="dfy-rule-toggle-wrap">
						<input type="checkbox" class="switcher-ui-toggle dfy-rule-toggle" ' . $checked . '
							data-id="' . esc_attr( $item['ID'] ) . '"
							data-nonce="' . esc_attr( $nonce ) . '"
						/>
					</label>
				</div>';
			case 'discount_valid':
				$valid = ! empty( $item['discount_valid'] ) ? $item['discount_valid'] : '';
				if ( empty( $valid ) ) {
					return '<span class="status success">' . esc_html__( 'Unlimited', 'discountify' ) . '</span>';
				}
				return esc_html( $valid );
			case $column_name:
				return $item[ $column_name ];
			default:
				isset( $item[ $column_name ] ) ? $item[ $column_name ] : '';
				break;
		}
	}

	private function get_discount_in( $item, $type = 'product' ) {
		$name = array();
		foreach ( $item as $key => $value ) {
			if ( $type === 'product' ) {
				$name[] = get_the_title( $value );
			} else {
				$term   = get_term_by( 'id', $value, 'product_cat', 'ARRAY_A' );
				$name[] = ! empty( $term['name'] ) ? $term['name'] : '';
			}
		}
		return implode( ', ', $name );
	}

	/**
	 * Main query and show function
	 */
	public function preparing_items() {
		$per_page              = 20;
		$column                = $this->get_columns();
		$hidden                = array();
		$meta_data             = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $column, $hidden, $sortable );
		$current_page          = $this->get_pagenum();
		$offset                = ( $current_page - 1 ) * $per_page;
		$this->process_bulk_action();

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Sorting parameters for display
		if ( isset( $_REQUEST['orderby'] ) && isset( $_REQUEST['order'] ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$args['orderby'] = sanitize_key( $_REQUEST['orderby'] );
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$args['order']   = sanitize_key( $_REQUEST['order'] );
		}
		$args['limit']  = $per_page;
		$args['offset'] = $offset;

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Filter display, bulk actions have nonce
		if ( ! empty( $_POST['discount_rules'] ) ) {
			$meta_data = array(
				array(
					'key'     => 'rules_type',
					// phpcs:ignore WordPress.Security.NonceVerification.Missing
					'value'   => sanitize_text_field( wp_unslash( $_POST['discount_rules'] ) ),
					'compare' => '=',
				),
			);
		}

		$get_data = Helper::get_all_rules( $args['limit'], $meta_data );

		$this->set_pagination_args(
			array(
				'total_items' => count( (array) Helper::get_all_rules() ),
				'per_page'    => $per_page,
			)
		);

		$this->items = $get_data;
	}
}
