<?php
namespace SabaiApps\Directories\Component\Location\Api;

class GoogleMapsPlacesApi extends AbstractGoogleMapsApi implements IPlacesApi {

	protected function _doGetInfo() {
		return array(
			'label' => __( 'Google Maps Place Details', 'directories-pro' ),
		);
	}

	public function locationApiLoad( array $settings ) {
		$this->_load( 'places' );
	}

	public function locationApiSettingsForm( array $settings, array $parents ) {
		return array(
			'places' => array(
				'#title'  => __( 'Google Maps Place Details', 'directories-pro' ),
				'#class'  => 'drts-form-label-lg',
				'#states' => array(
					'visible' => array(
						'[name="Map[lib][location_places]"]' => array(
							'type'  => 'value',
							'value' => 'location_googlemaps',
						),
					),
				),
				'#weight' => 20,
				'cache'   => $this->_application->System_Util_cacheSettingsForm( $settings['places']['cache'] ?? null, null, null, __( 'Cache API results', 'directories-pro' ) )
					+ array(
						'#description_no_escape' => true,
						'#description'           => sprintf(
							$this->_application->H( __( 'According to Google Maps %s, caching of API results is prohibited. Use this setting for testing purposes only and at your own risk.', 'directories-pro' ) ),
							'<a href="https://developers.google.com/maps/documentation/places/web-service/policies" target="_blank" rel="noopener noreferrer">' . $this->_application->H( __( 'Policies for Places API', 'directories-pro' ) ) . '</a>'
						),
					),
			),
		);
	}

	public function locationApiGetPlaceRating( $placeId, array $settings ) {
		$result = $this->_request( $placeId, $settings );
		return array(
			'rating' => $result['rating'],
			'count'  => $result['user_ratings_total'],
		);
	}

	public function locationApiGetPlaceOpeningHours( $placeId, array $settings ) {
		$result = $this->_request( $placeId, $settings );
		return $result['opening_hours'];
	}

	protected function _request( $placeId, array $settings ) {
		$url    = $this->_application->Map_GoogleMapsApi_url(
			'/place/details/json',
			array(
				'key'      => $settings['api']['key'],
				'place_id' => $placeId,
			)
		);
		$result = $this->_application->Map_GoogleMapsApi_request( $url, $settings['places']['cache'] );
		return $result['result'];
	}
}
