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

namespace DhlPolska\Admin\Shipments\Filter;

use DhlPolska\Shipment\ShipmentData;

/**
 * Filter shipments by shipment date.
 */
class ShipmentDateFilter implements FilterInterface {
	private const QUERY_VAR = 'shipment_date';

	/**
	 * @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 ( '' === $this->value ) {
			return $query_args;
		}

		$meta_query   = $query_args['meta_query'] ?? [];
		$meta_query[] = [
			'key'   => ShipmentData::OPTION_SHIPMENT_DATE,
			'value' => $this->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-shipment-date-filter.php';
	}

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

		return (string) $value;
	}
}
