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

namespace DhlPolska\Admin\Shipments\Filter;

use DhlPolska\Shipment\DhlServices;
use DhlPolska\Shipment\ShipmentData;

/**
 * Filter shipments by DHL service.
 */
class ServiceFilter implements FilterInterface {

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

	/**
	 * @var array<string, string>
	 */
	private array $services;

	public function __construct( string $value = '' ) {
		$this->services = ( new DhlServices() )->get_all_services();
		$sanitized      = sanitize_key( $value );
		$this->value    = isset( $this->services[ $sanitized ] ) ? $sanitized : '';
	}

	/**
	 * @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_SERVICE,
			'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 {
		$services = $this->services;
		$value    = $this->value;

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