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

namespace DhlPolska\Admin\Shipments\Filter;

/**
 * Filter shipments by status.
 */
class StatusFilter implements FilterInterface {
	private const QUERY_VAR = 'status';

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

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

	public function __construct() {
		$this->statuses = $this->get_statuses();
		$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 ) {
			$query_args['post_status'] = $this->value;
		}

		return $query_args;
	}

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

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

	/**
	 * @return array<string, string>
	 */
	private function get_statuses(): array {
		$statuses = get_post_stati( [ 'show_in_admin_all_list' => true ], 'objects' );
		$labels   = [];

		foreach ( $statuses as $status_key => $status_obj ) {
			if ( 0 !== strpos( $status_key, 'fs-' ) ) {
				continue;
			}

			$labels[ $status_key ] = $status_obj->label;
		}

		return $labels;
	}

	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;
	}
}
