<?php
namespace SabaiApps\Directories\Component\Booking\FieldWidget;

use SabaiApps\Directories\Component\Field\Widget\AbstractWidget;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Calendar\CalendarComponent;

class SpacesFieldWidget extends AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'       => __( 'Booking Spaces', 'directories-pro' ),
			'field_types' => array( $this->_name ),
		);
	}

	public function fieldWidgetForm( IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( isset( $value ) ) {
			// Do not allow modifying spaces if value is already set
			$value = intval( $value );
			return array(
				'#type'   => 'item',
				'#markup' => $value . '<input type="hidden" value="' . $value . '" name="' . $this->_application->Form_Form_fieldName( $parents ) . '" />',
			);
		}
		if ( $this->_application->getPlatform()->isAdmin()
			|| empty( $_REQUEST['occurrence_hash'] )
			|| ( ! $occurrence = $this->_application->Calendar_Calendar_isValidOccurrence( $_REQUEST['occurrence_hash'], CalendarComponent::OCCURRENCE_STATUS_ACTIVE ) )
			|| empty( $occurrence->slot_data_snapshot['booking_allow'] )
			|| ( ! $spaces_available = $this->_application->Booking_Util_spacesAvailable( $occurrence, $value ) )
		) {
			return;
		}

		return array(
			'#type'          => 'number',
			'#integer'       => true,
			'#min_value'     => 1,
			'#max_value'     => isset( $entity ) ? null : $spaces_available, // prevent error when editing existing booking
			'#default_value' => $value ?? 1,
		);
	}
}
