<?php
/**
 * This file describes class for render view price tracker subscriptions lists in WordPress admin panel.
 *
 * @package woodmart.
 */

namespace XTS\Modules\Price_Tracker\List_Table;

use WP_List_Table;
use XTS\Modules\Price_Tracker\DB_Storage;

if ( ! defined( 'ABSPATH' ) ) {
	exit( 'No direct script access allowed' );
}

/**
 * Create a new table class that will extend the WP_List_Table.
 */
class Products_Table extends WP_List_Table {
	/**
	 * DB_Storage instance.
	 *
	 * @var DB_Storage
	 */
	protected $db_storage;

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( ! woodmart_get_opt( 'price_tracker_enabled' ) || ! woodmart_woocommerce_installed() ) {
			return;
		}

		parent::__construct();
	}

	/**
	 * Define what data to show on each column of the table.
	 *
	 * @param array  $item        Data.
	 * @param string $column_name - Current column name.
	 *
	 * @return mixed
	 */
	public function column_default( $item, $column_name ) {
		return array_key_exists( $column_name, $item ) ? esc_html( $item[ $column_name ] ) : '';
	}

	/**
	 * Prints checkbox column.
	 *
	 * @param array $item Item to use to print record.
	 * @return string
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="products_ids[]" value="%1$s" />',
			! empty( $item['variation_id'] ) ? $item['variation_id'] : $item['product_id']
		);
	}

	/**
	 * Prints thumbnail column.
	 *
	 * @param array $item Item to use to print record.
	 * @return string
	 */
	public function column_thumb( $item ) {
		$product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
		$product    = wc_get_product( $product_id );

		if ( ! $product ) {
			return '';
		}
		?>
		<a href="<?php echo esc_url( get_edit_post_link( $product->get_id() ) ?? '' ); ?>">
			<?php echo $product->get_image( 'thumbnail' ); // phpcs:ignore. ?>
		</a>
		<?php
	}

	/**
	 * Prints column for produt name.
	 *
	 * @param array $item Item to use to print record.
	 * @return string
	 */
	public function column_name( $item ) {
		$product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
		$product    = wc_get_product( $product_id );

		if ( ! $product ) {
			return '';
		}

		$product_edit_url = get_edit_post_link( $item['product_id'] );
		$actions          = array(
			'product_id' => sprintf( 'ID: %s', esc_html( $item['product_id'] ) ),
			'edit'       => sprintf( '<a href="%s" title="%s">%s</a>', $product_edit_url, esc_html__( 'Edit this item', 'woodmart' ), esc_html__( 'Edit', 'woodmart' ) ),
			'view_users' => sprintf(
				'<a href="%s" title="%s">%s</a>',
				esc_url(
					add_query_arg(
						array(
							'page'         => 'xts-price-tracker-page',
							'tab'          => 'users',
							'product_id'   => $item['product_id'],
							'variation_id' => $item['variation_id'],
						),
						admin_url( 'edit.php?post_type=product' )
					)
				),
				esc_html__( 'View a list of customers subscribed to price drop notifications for this product.', 'woodmart' ),
				esc_html__( 'View customers', 'woodmart' )
			),
		);

		if ( in_array( $product->get_type(), array( 'variation', 'subscription_variation' ), true ) ) {
			$attributes = array();

			foreach ( $product->get_attributes() as $taxonomy => $value ) {
				$attributes[ wc_attribute_label( $taxonomy ) ] = $value;
			}
		}

		?>
		<div class="product-details">
			<strong>
				<a class="row-title" href="<?php echo esc_url( $product->get_permalink() ); ?>">
					<?php echo esc_html( $product->get_title() ); ?>
				</a>
			</strong>

			<?php if ( isset( $attributes ) && ! empty( $attributes ) ) : ?>
				<div class="xts-pt-attributes">
					<div class="view">
						<table cellspacing="0" class="xts-pt-variations">
							<?php foreach ( $attributes as $label => $value ) : ?>
								<tr>
									<th><?php echo wp_kses_post( ucfirst( $label ) ); ?>:</th>
									<td><?php echo wp_kses_post( ucfirst( $value ) ); ?></td>
								</tr>
							<?php endforeach; ?>
						</table>
					</div>
				</div>
			<?php endif; ?>

			<?php echo $this->row_actions( $actions ); // phpcs:ignore. ?>
		</div>
		<?php
	}

	/**
	 * Prints column for produt stock status.
	 *
	 * @param array $item Item to use to print record.
	 * @return string
	 */
	public function column_is_in_stock( $item ) {
		$product_id = $item['variation_id'] ? $item['variation_id'] : $item['product_id'];
		$product    = wc_get_product( $product_id );

		if ( ! $product ) {
			return '';
		}

		if ( $product->is_in_stock() ) {
			$status_class = 'instock';
			$status_label = esc_html__( 'In stock', 'woodmart' );
		} else {
			$status_class = 'outofstock';
			$status_label = esc_html__( 'Out of stock', 'woodmart' );
		}

		ob_start();
		?>
		<mark class="<?php echo esc_attr( $status_class ); ?>">
			<?php echo esc_html( $status_label ); ?>
		</mark>
		<?php

		return ob_get_clean();
	}

	/**
	 * Prints column for user name.
	 *
	 * @param array $item Item to use to print record.
	 * @return string
	 */
	public function column_users( $item ) {
		$column_content = $item['user_count'];

		return sprintf(
			'<a href="%s">%d</a>',
			esc_url(
				add_query_arg(
					array(
						'page'         => 'xts-price-tracker-page',
						'tab'          => 'users',
						'product_id'   => $item['product_id'],
						'variation_id' => $item['variation_id'],
					),
					admin_url( 'edit.php?post_type=product' )
				)
			),
			$column_content
		);
	}

	/**
	 * Override the parent columns method.
	 * Defines the columns to use in your listing table.
	 *
	 * @return array
	 */
	public function get_columns() {
		return array(
			'cb'          => '<input type="checkbox" />',
			'thumb'       => '<span class="wc-image tips" data-tip="' . esc_attr__( 'Image', 'woodmart' ) . '">' . esc_html__( 'Image', 'woodmart' ) . '</span>',
			'name'        => esc_html__( 'Name', 'woodmart' ),
			'is_in_stock' => esc_html__( 'Stock', 'woodmart' ),
			'users'       => esc_html__( 'Users', 'woodmart' ),
		);
	}

	/**
	 * Define which columns are hidden.
	 *
	 * @return array
	 */
	public function get_hidden_columns() {
		return array();
	}

	/**
	 * Define the sortable columns.
	 *
	 * @return array
	 */
	public function get_sortable_columns() {
		return array(
				'users' => array( 'user_count', false ),
		);
	}

	/**
	 * Sets bulk actions for table.
	 *
	 * @return array Array of available actions.
	 */
	public function get_bulk_actions() {
		return array(
			'delete' => esc_html__( 'Delete', 'woodmart' ),
		);
	}

	/**
	 * Delete on bulk action.
	 *
	 * @codeCoverageIgnore
	 *
	 * @return void
	 */
	public function process_bulk_action() {
		if ( ! isset( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'bulk-' . $this->_args['plural'] ) ) { // phpcs:ignore.
			return;
		}

		// Detect when a bulk action is being triggered...
		$products_ids = isset( $_REQUEST['products_ids'] ) ? (array) $_REQUEST['products_ids'] : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput

		if ( 'delete' === $this->current_action() && ! empty( $products_ids ) ) {
			foreach ( $products_ids as $product_id ) {
				try {
					$this->db_storage->unsubscribe_by_product_id( intval( $product_id ) );
				} catch ( \Exception $e ) {
					error_log( 'process bulk action error: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
					continue;
				}
			}

			wp_safe_redirect( admin_url( '/edit.php?post_type=product&page=xts-price-tracker-page' ) );
			die();
		}
	}

	/**
	 * Prepare the items for the table to process.
	 *
	 * @return void
	 */
	public function prepare_items() {
		$this->db_storage = DB_Storage::get_instance();
		$columns          = $this->get_columns();
		$hidden           = $this->get_hidden_columns();
		$sortable         = $this->get_sortable_columns();
		$user_id          = get_current_user_id();

		$data = $this->table_data();

		$order_by = 'created_date';
		$order    = 'desc';

		// If orderby is set, use this as the sort column.
		if ( ! empty( $_GET['orderby'] ) ) { // phpcs:ignore.
			$order_by = $_GET['orderby']; // phpcs:ignore.
		}

		// If order is set use this as the order.
		if ( ! empty( $_GET['order'] ) ) { // phpcs:ignore.
			$order = $_GET['order']; // phpcs:ignore.
		}

		woodmart_sort_data( $data, $order_by, $order );

		$per_page     = ! empty( get_user_meta( $user_id, 'price_tracker_per_page', true ) ) ? get_user_meta( $user_id, 'price_tracker_per_page', true ) : 20;
		$current_page = $this->get_pagenum();
		$total_items  = count( $data );

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

		$data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page );

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

		$this->process_bulk_action();
	}

	/**
	 * Get the table data.
	 *
	 * @return array
	 */
	private function table_data() {
		global $wpdb;

		$where_query = array();
		$search      = isset( $_REQUEST['s'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) : false; // phpcs:ignore.
		$_product_id = isset( $_REQUEST['_product_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_product_id'] ) ) : false; // phpcs:ignore.
		$_user_id    = isset( $_REQUEST['_user_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_user_id'] ) ) : false; // phpcs:ignore.
		$_user_email = isset( $_REQUEST['_user_email'] ) ? sanitize_email( wp_unslash( $_REQUEST['_user_email'] ) ) : false; // phpcs:ignore.
		$cache_key   = $this->get_table_data_cache_key( $search, $_product_id, $_user_id, $_user_email );
		$found       = false;

		if ( $search ) {
			$where_query[] = $wpdb->prepare( "$wpdb->posts.`post_title` LIKE %s", '%' . $wpdb->esc_like( $search ) . '%' );
		}

		if ( $_product_id ) {
			$where_query[] = $wpdb->prepare( "$wpdb->wd_price_tracker.`product_id` = %d OR $wpdb->wd_price_tracker.`variation_id` = %d", $_product_id, $_product_id );
		}

		if ( $_user_id ) {
			$where_query[] = $wpdb->prepare( "$wpdb->wd_price_tracker.user_id = %d", $_user_id );
		}

		if ( $_user_email ) {
			$where_query[] = $wpdb->prepare( "$wpdb->wd_price_tracker.user_email = %s", $_user_email );
		}

		$where_query_text = ! empty( $where_query ) ? ' WHERE ' . implode( ' AND ', $where_query ) : '';
		$cached_data      = wp_cache_get( $cache_key, '', false, $found );

		if ( $found ) {
			return $cached_data;
		}

		// phpcs:disable WordPress.DB
		$table_data = $wpdb->get_results(
			"SELECT
				$wpdb->wd_price_tracker.`product_id`,
				$wpdb->wd_price_tracker.`variation_id`,
				COUNT( DISTINCT $wpdb->wd_price_tracker.`user_email` ) as `user_count`,
				MAX( $wpdb->wd_price_tracker.`created_date_gmt` ) as `created_date`
			FROM $wpdb->wd_price_tracker
			INNER JOIN $wpdb->posts
				ON $wpdb->posts.`ID` = $wpdb->wd_price_tracker.`product_id`"
					. $where_query_text .
					" GROUP BY
				$wpdb->wd_price_tracker.`product_id`,
				$wpdb->wd_price_tracker.`variation_id`
			;",
				ARRAY_A
		);
		// phpcs:enable WordPress.DB

		wp_cache_set( $cache_key, $table_data, '', 300 );

		return $table_data;
	}

	/**
	 * Build cache key for the current table query.
	 *
	 * @param string|false     $search Search term.
	 * @param string|int|false $_product_id Product filter.
	 * @param string|int|false $_user_id User ID filter.
	 * @param string|false     $_user_email User email filter.
	 *
	 * @return string
	 */
	private function get_table_data_cache_key( $search, $_product_id, $_user_id, $_user_email ) {
		$cache_version = (int) get_option( DB_Storage::CACHE_VERSION_OPTION, 1 );

		return 'wd_price_tracker_table_data_' . md5( wp_json_encode( array( (string) $search, (int) $_product_id, (int) $_user_id, (string) $_user_email, $cache_version ) ) );
	}

	/**
	 * Print filters for current table
	 *
	 * @codeCoverageIgnore
	 *
	 * @param string $which Top / Bottom.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	protected function extra_tablenav( $which ) {
		if ( 'top' !== $which ) {
			return;
		}

		$reset_link = add_query_arg(
			array(
				'page' => 'xts-price-tracker-page',
			),
			admin_url( '/edit.php?post_type=product' )
		);

		woodmart_add_list_table_filters( $reset_link );
	}
}
