<?php

namespace SugarCalendarBookings\Locations;

use SugarCalendarBookings\Appointments\AppointmentModel;

/**
 * Location factory.
 *
 * @since 1.0.0
 */
class LocationFactory {

	/**
	 * Create a location object from an array.
	 *
	 * @since 1.0.0
	 *
	 * @param array $data The location data.
	 *
	 * @return AbstractLocation|null
	 */
	public static function from_array( $data ) {

		$type     = $data['type'] ?? null;
		$location = null;

		if ( $type === 'in_person' && isset( $data['id'] ) ) {
			$location = InPersonLocation::get( $data['id'] );
		} elseif ( $type === 'online' && isset( $data['uid'] ) ) {
			$location = OnlineLocation::get( $data['uid'] );
		}

		return $location;
	}

	/**
	 * Create a location object from an appointment.
	 *
	 * @since 1.0.0
	 *
	 * @param AppointmentModel $appointment The appointment.
	 *
	 * @return AbstractLocation|null
	 */
	public static function from_appointment( $appointment ) {

		if ( ! empty( $appointment->location_id ) ) {
			$in_person_location = $appointment->location;

			if ( $in_person_location ) {
				return new InPersonLocation( $in_person_location );
			}

			return null;
		}

		$online_location = $appointment->online_location;

		if ( $online_location ) {
			return OnlineLocation::from_array( $online_location );
		}

		return null;
	}
}
