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

use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Field\Renderer\AbstractRenderer;

class PlaceIdFieldRenderer extends AbstractRenderer {

	protected static $_jsLoaded = array();

	protected function _fieldRendererInfo() {
		return array(
			'label'            => __( 'Google Maps place details', 'directories-pro' ),
			'field_types'      => array( 'string' ),
			'default_settings' => array(
				'type' => 'rating',
			),
			'inlineable'       => true,
		);
	}

	public function fieldRendererSupports( Bundle $bundle, IField $field ) {
		$settings = $field->getFieldSettings();
		return isset( $settings['char_validation'] )
			&& $settings['char_validation'] === 'location_googlemaps_place_id'
			&& $this->_application->getComponent( 'Map' )->getConfig( 'lib', 'map' ) === 'googlemaps'
			&& $this->_application->getComponent( 'Map' )->getConfig( 'lib', 'location_places' ) === 'location_googlemaps';
	}

	protected function _fieldRendererSettingsForm( IField $field, array $settings, array $parents = array() ) {
		return array(
			'type' => array(
				'#type'          => 'select',
				'#options'       => array(
					'rating'        => __( 'Rating', 'directories-pro' ),
					'opening_hours' => __( 'Opening Hours', 'directories-pro' ),
				),
				'#default_value' => $settings['type'],
			),
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		if ( ! isset( self::$_jsLoaded[''] ) ) {
			if ( ! $this->_application->Map_Api_load() ) {
				return;
			}

			$this->_application->Location_Api_load( array( 'location_places' => true ) );
			self::$_jsLoaded[''] = true;
		}

		$type = isset( $settings['type'] ) ? $settings['type'] : 'rating';
		switch ( $type ) {
			case 'opening_hours':
				$time_format        = $this->_application->getPlatform()->getTimeFormat();
				$use_24_hour_format = strpos( $time_format, 'G' ) !== false
					|| strpos( $time_format, 'H' ) !== false;
				if ( ! isset( self::$_jsLoaded[ $type ] ) ) {
					$days = array();
					foreach ( $this->_application->Days() as $i => $day ) {
						if ( $i === 7 ) {
							$i = 0;
						}
						$days[] = $i . ',"' . $this->_application->H( $day ) . '"';
					}
					$this->_application->getPlatform()->addJsFile( 'location-googlemaps-opening-hours.min.js', 'drts-location-googlemaps-opening-hours', 'drts', 'directories-pro' )
						->addJs(
							'$(\'.drts-location-field-place-opening-hours [data-place-id]\').each(function(){
    var $this = $(this);
    DRTS.Location.api.getPlaceDetails(
        $this.data("place-id"),
        "opening_hours",
        function(results){
            $this.parent().html(DRTS.DirectoryPro.openingHours(results.periods, results.open_now, {
                closedStr: "' . $this->_application->H( _x( 'Closed', 'opening hours', 'directories-pro' ) ) . '",
                use24HourFormat: ' . ( $use_24_hour_format ? 'true' : 'false' ) . ',
                daysOfWeek: new Map([[' . implode( '],[', $days ) . ']])
            }));
        },
        function (err) { console.log(err); $this.text(err.message).css("visibility", "visible"); }
    );
});',
							true
						);
					self::$_jsLoaded[ $type ] = true;
				}
				$ret = array();
				foreach ( $values as $key => $value ) {
					$ret[] = '<div class="' . DRTS_BS_PREFIX . 'list-group" style="visibility:hidden;" data-place-id="' . $this->_application->H( $value ) . '"></div>';
				}
				return array(
					'class' => 'drts-location-field-place-opening-hours',
					'html'  => implode( $settings['_separator'], $ret ),
				);
				break;
			case 'rating':
				if ( ! isset( self::$_jsLoaded[ $type ] ) ) {
					$this->_application->getPlatform()->addJs(
						'$(\'.drts-location-field-place-rating [data-place-id]\').each(function(){
    var $this = $(this);
    DRTS.Location.api.getPlaceDetails(
        $this.data("place-id"),
        "rating",
        function(results){
            var rating = results.rating;
            var count = results.count;
            $this.find(".drts-voting-rating-average").text(rating).end()
                .find(".drts-voting-rating-count").text(count).end()
                .find(".drts-voting-rating-stars").removeClass("drts-voting-rating-stars-0").addClass("drts-voting-rating-stars-" + ((rating - (rating % 0.5)) * 10)).end()
                .css("visibility", "visible");
        },
        function (err) { console.log(err); $this.text(err.message).css("visibility", "visible"); }
    );
});',
						true
					);
					self::$_jsLoaded[ $type ] = true;
				}
				$ret = array();
				foreach ( $values as $key => $value ) {
					$ret[] = '<span style="visibility:hidden;" data-place-id="' . $this->_application->H( $value ) . '">' . $this->_application->Voting_RenderRating(
						0,
						array(
							'avg_first' => true,
							'count'     => 0,
						)
					) . '</span>';
				}
				return array(
					'class' => 'drts-location-field-place-rating',
					'html'  => implode( $settings['_separator'], $ret ),
				);
		}
	}
}
