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

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

class DateListFieldRenderer extends AbstractRenderer {

	protected function _fieldRendererInfo() {
		return array(
			'label'            => __( 'Date List', 'directories-pro' ),
			'field_types'      => array( 'calendar_slot' ),
			'default_settings' => array(
				'_separator' => ', ',
			),
			'accept_multiple'  => false,
		);
	}

	protected function _fieldRendererRenderField( IField $field, array &$settings, IEntity $entity, array $values, ?array $context = null, $more = 0 ) {
		$slots = array();
		foreach ( $values as $value ) {
			$slots[ $value['slot_id'] ] = $value['title'];
		}
		$occurrences         = $this->_application->getModel( 'Occurrence', 'Calendar' )
			->slotId_in( array_keys( $slots ) )
			->startDate_isOrGreaterThan( time() )
			->fetch( 0, 0, 'start_date', 'ASC' );
		$occurrences_by_slot = $ret = array();
		foreach ( $occurrences as $occurrence ) {
			$occurrences_by_slot[ $occurrence->slot_id ][] = $this->_application->System_Date( $occurrence->start_date, true );
		}
		foreach ( $occurrences_by_slot as $slot_id => $dates ) {
			if ( strlen( $slots[ $slot_id ] ) ) {
				$ret[] = sprintf(
					__( '%1$s (%2$s)', 'directories-pro' ),
					$this->_application->H( $slots[ $slot_id ] ),
					implode( ', ', $dates )
				);
			} else {
				$ret[] = implode( ', ', $dates );
			}
		}
		return implode( $settings['_separator'], $ret );
	}
}
