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

namespace DhlPolska\Admin\Shipments\Filter;

/**
 * Filter shipments by status.
 */
class StatusFilter implements FilterInterface {

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

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

	public function __construct( string $value = '' ) {
		$this->statuses = $this->get_statuses();
		$sanitized      = sanitize_key( $value );
		$this->value    = isset( $this->statuses[ $sanitized ] ) ? $sanitized : '';
	}

	/**
	 * @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;
	}
}
