<?php
namespace BerryPress\LiveCarts;

defined('ABSPATH') || exit;

class CartsListTable extends \WP_List_Table {

	private $statuses;

	public function __construct() {
		parent::__construct(['singular' => 'cart', 'plural' => 'carts']);
		$this->statuses = LiveCarts::instance()->getCartStatuses();
	}

	public function get_views() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent filtering
		$status = empty($_REQUEST['status']) ? 'all' : sanitize_key($_REQUEST['status']);
		$views = [
			'all' => '<a href="'.esc_url(remove_query_arg('status')).'"'.($status == 'all' ? ' class="current"' : '').'>'.esc_html__('All', 'live-carts-for-woocommerce').'</a>'
		];
		foreach ($this->statuses as $statusId => $statusDisplay) {
			$views[$statusId] = '<a href="'.esc_url(add_query_arg('status', rawurlencode($statusId))).'"'.($status == $statusId ? ' class="current"' : '').'>'.esc_html($statusDisplay).'</a>';
		}
		return $views;
	}
	
	public function get_columns() {
		$columns = [
			'cb' => esc_html__('Select Cart', 'live-carts-for-woocommerce'),
			'cart_id' => esc_html__('Cart ID', 'live-carts-for-woocommerce'),
			'status' => esc_html__('Status', 'live-carts-for-woocommerce'),
			'user' => esc_html__('User', 'live-carts-for-woocommerce'),
		];
		if ( ! get_option( 'phplugins_carts_no_ip' ) ) {
			$columns['ip_address'] = esc_html__( 'IP Address', 'live-carts-for-woocommerce' );
		}
		$columns['last_seen'] = esc_html__('Last Seen', 'live-carts-for-woocommerce');
		$columns['coupon'] = esc_html__('Coupon(s)', 'live-carts-for-woocommerce');
		$columns['value'] = esc_html__('Cart Value', 'live-carts-for-woocommerce');
		return $columns;
	}
	
	public function get_bulk_actions() {
		return [
			'delete' => esc_html__('Delete', 'live-carts-for-woocommerce')
		];
	}
	
	public function column_cb( $row ) {
		?>
		<input id="cb-select-<?php echo((int) $row['cart_id']); ?>" type="checkbox" name="post[]" value="<?php echo((int) $row['cart_id']); ?>" />
		<label for="cb-select-<?php echo((int) $row['cart_id']); ?>">
			<span class="screen-reader-text">
			<?php
				/* translators: %s: cart ID */
				printf( esc_html__( 'Select cart %s', 'live-carts-for-woocommerce' ), esc_html( LiveCarts::formatCartId($row['cart_id']) ) );
			?>
			</span>
		</label>
		<?php
	}

	public function prepare_items() {
		global $wpdb;
		$perPage = $this->get_items_per_page('berrypress_page_live-carts-for-woocommerce_per_page');
		
		$filterSql = '';
		$params = [0];
		
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent filtering
		if (isset($_REQUEST['status']) && isset($this->statuses[ $_REQUEST['status'] ])) {
			$filterSql .= ' AND status=%s';
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent filtering
			$params[] = sanitize_key($_REQUEST['status']);
		}
		
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent searching
		if (!empty($_REQUEST['s'])) {
			$filterSql .= ' AND cart_id=%s';
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent searching
			$params[] = LiveCarts::unformatCartId(sanitize_text_field(wp_unslash($_REQUEST['s'])));
		}
		
		list($filterSql, $params) = apply_filters('phplugins_live_carts_list_filter_sql', [$filterSql, $params]);
		
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $filterSql is built with placeholders, prepared on same line
		$count = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM '.$wpdb->prefix.'phplugins_carts WHERE archived=%d'.$filterSql, $params));
		
		$sql = 'SELECT cart_id, status, user_id, last_seen, coupon, last_url, value, ip_address
				FROM '.$wpdb->prefix.'phplugins_carts
				WHERE archived=%d'
				.$filterSql.'
				ORDER BY last_seen DESC
				LIMIT %d,%d';
		
		$params[] = ($this->get_pagenum() - 1) * $perPage;
		$params[] = $perPage;
	
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- prepared on next line
		$query = $wpdb->prepare($sql, $params);
		
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $sql contains dynamic $filterSql with placeholders, prepared above
		$this->items = $wpdb->get_results($query, ARRAY_A);
		
		
		$this->set_pagination_args([
			'total_items' => (int) $count,
			'per_page' => $perPage
		]);
	}

	protected function column_cart_id($row) {
		return '<a href="'.esc_url(add_query_arg('cart_id', (int) $row['cart_id'])).'">'.LiveCarts::formatCartId($row['cart_id']).'</a>';
	}

	protected function _column_status($row, $classNames, $dataAttrs, $isPrimary) {
		return '<td class="'.esc_attr($classNames.' phplugins-live-carts-'.$row['status']).'" '
					// values in $dataAttrs were already escaped
					.$dataAttrs
				.'>'
					.esc_html(
						isset($this->statuses[$row['status']])
							? $this->statuses[$row['status']]
							: $row['status']
					)
				.'</td>';
	}
	
	protected function column_last_seen($row) {
		return $row['last_url']
					? sprintf(
						// translators: first %s is a timestamp, second %s is a URL
						esc_html__('%1$s at %2$s', 'live-carts-for-woocommerce'),
						esc_html(get_date_from_gmt($row['last_seen'], LiveCarts::instance()->getTimestampFormat())),
						'<a href="'.esc_url($row['last_url']).'" target="_blank">'.esc_url($row['last_url']).'</a>'
					)
					: esc_html(get_date_from_gmt($row['last_seen'], LiveCarts::instance()->getTimestampFormat()));
	}
	
	protected function column_coupon($row) {
		return esc_html($row['coupon']);
	}
	
	protected function column_user($row) {
		if ($row['user_id']) {
			$user = get_userdata($row['user_id']);
			if ($user) {
				$userDisplayName = trim($user->first_name.' '.$user->last_name);
				if (empty($userDisplayName)) {
					$userDisplayName = $user->user_login;
				}
			}
		}
		return empty($user) ? esc_html_e('Guest/Unknown', 'live-carts-for-woocommerce') : '<a href="'.esc_url(get_edit_user_link($user->ID)).'" target="_blank">'.esc_html($userDisplayName).'</a>';
	}

	protected function column_ip_address($row) {
		return esc_html($row['ip_address']);
	}

	protected function column_value($row) {
		return wc_price((float) $row['value']);
	}

	public function get_table_classes() {
		return array( 'widefat', 'table-view-list', 'fixed', 'striped', 'berrypress_page_live-carts-for-woocommerce', 'berrypress-table' );
	}

	public function search_box( $text, $input_id ) {
	    // Replicate parent::search_box but add placeholder attribute and custom classes
		
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent searching
	    if ( empty( $_REQUEST['s'] ) && ! $this->has_items() ) {
	        return;
	    }

	    $input_id = $input_id . '-search-input';

	    echo '<p class="search-box berrypress-search-box">';
	    echo '<label class="screen-reader-text" for="' . esc_attr( $input_id ) . '">' . esc_html( $text ) . ':</label>';
		
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- non-persistent searching
	    echo '<input type="search" id="' . esc_attr( $input_id ) . '" class="berrypress-search-input" name="s" placeholder="' . esc_attr( $text ) . '" value="' . esc_attr( sanitize_text_field(wp_unslash($_REQUEST['s'] ?? '')) ) . '" />';
	    submit_button( esc_html__( 'Search', 'live-carts-for-woocommerce' ), 'berrypress-btn berrypress-btn-secondary', '', false, array( 'id' => 'search-submit' ) );
	    echo '</p>';
	}


}
