<?php
/**
 * Destination registry.
 *
 * @package Ordsync
 */

defined( 'ABSPATH' ) || exit;

/**
 * Builds one object per configured destination slot, keyed by instance id.
 */
class Ordsync_Destinations {

	/**
	 * Built instances, keyed by instance id.
	 *
	 * @var Ordsync_Destination[]|null
	 */
	private static $items = null;

	/**
	 * Class name for each destination type.
	 *
	 * @return array type => class name
	 */
	public static function classes() {

		$map = array(
			'sheets'  => 'Ordsync_Dest_Sheets',
			'webhook' => 'Ordsync_Dest_Webhook',
			'email'   => 'Ordsync_Dest_Email',
		);

		/**
		 * Filter the destination class map. Premium destinations hook here.
		 *
		 * @param array $map type => class name.
		 */
		return apply_filters( 'ordsync_destination_classes', $map );
	}

	/**
	 * Every destination instance across every type and slot.
	 *
	 * @return Ordsync_Destination[]
	 */
	public static function all() {

		if ( null !== self::$items ) {
			return self::$items;
		}

		self::$items = array();

		foreach ( self::classes() as $type => $class ) {

			if ( ! class_exists( $class ) ) {
				continue;
			}

			$slots = Ordsync_Settings::slots( $type );

			foreach ( $slots as $index => $config ) {

				$instance = new $class( $config, $index );

				self::$items[ $instance->id() ] = $instance;
			}
		}

		return self::$items;
	}

	/**
	 * One destination by instance id, for example "sheets" or "sheets_1".
	 *
	 * @param string $id Instance id.
	 * @return Ordsync_Destination|null
	 */
	public static function get( $id ) {
		$all = self::all();
		return isset( $all[ $id ] ) ? $all[ $id ] : null;
	}

	/**
	 * Only the enabled, configured instances.
	 *
	 * @return Ordsync_Destination[]
	 */
	public static function enabled() {
		return array_filter(
			self::all(),
			function ( $destination ) {
				return $destination->is_enabled();
			}
		);
	}

	/**
	 * Forget cached instances (used after saving settings).
	 *
	 * @return void
	 */
	public static function flush() {
		self::$items = null;
	}
}
