<?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 {
	private const QUERY_VAR = 'service';

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

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

	public function __construct() {
		$this->services = ( new DhlServices() )->get_all_services();
		$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_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';
	}

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

		return (string) $value;
	}
}
