<?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 {

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

	public function __construct( string $value = '' ) {
		$this->value = $this->sanitize_value( $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 sanitize_value( string $value ): string {
		$filter = sanitize_key( $value );
		if ( in_array( $filter, [ 'with', 'without' ], true ) ) {
			return $filter;
		}

		return '';
	}
}
