<?php

namespace SugarCalendarBookings\Services\SmartTags;

use SugarCalendarBookings\Services\ServiceModel;
use SugarCalendarBookings\Locations\OnlineLocation;
use SugarCalendarBookings\Support\SmartTags\SmartTagInterface;

/**
 * Service Location smart tag.
 *
 * @since 1.0.0
 */
class ServiceLocationsSmartTag implements SmartTagInterface {

	/**
	 * Service model instance.
	 *
	 * @since 1.0.0
	 *
	 * @var ServiceModel
	 */
	private $service;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param ServiceModel $service Service model instance.
	 */
	public function __construct( ServiceModel $service ) {

		$this->service = $service;
	}

	/**
	 * Get the smart tag key.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_key() {

		return '{service_locations}';
	}

	/**
	 * Get the smart tag value.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_value() {

		$location_names = array_merge(
			$this->get_in_person_location_names(),
			$this->get_online_location_names()
		);

		if ( empty( $location_names ) ) {
			return '';
		}

		return implode( ', ', $location_names );
	}

	/**
	 * Get in-person location names.
	 *
	 * @since 1.0.0
	 *
	 * @return array Array of in-person location names.
	 */
	private function get_in_person_location_names() {

		if ( empty( $this->service->locations ) ) {
			return [];
		}

		$names = [];

		foreach ( $this->service->locations as $location ) {
			$names[] = $location->name;
		}

		return $names;
	}

	/**
	 * Get online location names.
	 *
	 * @since 1.0.0
	 *
	 * @return array Array of online location names.
	 */
	private function get_online_location_names() {

		if ( empty( $this->service->online_locations ) ) {
			return [];
		}

		$names = [];

		foreach ( $this->service->online_locations as $location ) {
			$online_location = OnlineLocation::from_array( $location );

			if ( $online_location ) {
				$names[] = $online_location->get_display_name();
			}
		}

		return $names;
	}
}
