<?php
/**
 * CourierBookingFilter
 *
 * @package DhlPolska\Admin\Shipments\Filter
 */

namespace DhlPolska\Admin\Shipments\Filter;

use DhlPolska\Shipment\ShipmentData;

/**
 * Filter shipments by courier booking.
 */
class CourierBookingFilter implements FilterInterface {
	private const QUERY_VAR = 'courier_booking';

	/**
	 * @var string
	 */
	private string $value;

	public function __construct() {
		$this->value = $this->get_request_value();
	}

	/**
	 * @param array<string, mixed> $query_args .
	 *
	 * @return array<string, mixed>
	 */
	public function apply( array $query_args ): array {
		if ( 'with' === $this->value ) {
			$meta_query   = $query_args['meta_query'] ?? [];
			$meta_query[] = [
				'key'     => ShipmentData::OPTION_COURIER_BOOKING_ID,
				'value'   => '',
				'compare' => '!=',
			];

			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Filters require meta query.
			$query_args['meta_query'] = $meta_query;
		}

		if ( 'without' === $this->value ) {
			$meta_query   = $query_args['meta_query'] ?? [];
			$meta_query[] = [
				'relation' => 'OR',
				[
					'key'     => ShipmentData::OPTION_COURIER_BOOKING_ID,
					'compare' => 'NOT EXISTS',
				],
				[
					'key'   => ShipmentData::OPTION_COURIER_BOOKING_ID,
					'value' => '',
				],
			];

			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Filters require meta query.
			$query_args['meta_query'] = $meta_query;
		}

		return $query_args;
	}

	public function render(): void {
		$value = $this->value;

		include __DIR__ . '/views/html-courier-booking-filter.php';
	}

	private function get_request_value(): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Uses list-table filters.
		$filter = isset( $_GET[ self::QUERY_VAR ] ) ? sanitize_key( wp_unslash( $_GET[ self::QUERY_VAR ] ) ) : '';

		if ( in_array( $filter, [ 'with', 'without' ], true ) ) {
			return $filter;
		}

		return '';
	}
}
