<?php
/**
 * Class PickupPointsFilter
 *
 * @package FS\InPost\PickupPoints
 */

namespace FS\InPost\PickupPoints;

use WPDesk_Paczkomaty_ShipX_Cache;

/**
 * Pickup Point Filter.
 */
class PickupPointsFilter {

	/**
	 * @var array
	 */
	private $pickup_points;

	/**
	 * @param array $pickup_points .
	 */
	public function __construct( array $pickup_points ) {
		$this->pickup_points = $pickup_points;
	}

	/**
	 * @param array $types .
	 *
	 * @return array
	 */
	public function get_filtered_by_type( array $types = [] ): array {
		// Filtering points by type.
		if ( ! $types ) {
			return $this->pickup_points;
		}

		$types_count_required = 0;

		if ( in_array( WPDesk_Paczkomaty_ShipX_Cache::PARCEL_LOCKER_ONLY_STRING, $types, true ) ) {
			$types_count_required = 1;

			$types = WPDesk_Paczkomaty_ShipX_Cache::PARCEL_LOCKER;
		}

		$this->pickup_points = array_filter(
			$this->pickup_points,
			function ( $point_data ) use ( $types, $types_count_required ) {
				return $this->has_type( $types, $point_data['type'], $types_count_required );
			}
		);

		return $this->pickup_points;
	}

	/**
	 * @param string[] $types                .
	 * @param string[] $point_types          .
	 * @param int      $types_count_required .
	 *
	 * @return bool
	 */
	private function has_type( array $types, array $point_types, int $types_count_required ): bool {
		foreach ( $types as $type ) {
			if ( in_array( $type, $point_types ) ) {
				if ( $types_count_required > 0 && count( $point_types ) === $types_count_required ) {
					return true;
				}

				if ( $types_count_required === 0 ) {
					return true;
				}
			}
		}

		return false;
	}
}
