<?php
namespace JET_ABAF\Workflows\Events;

use JET_ABAF\Workflows\Actions_Dispatcher;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

class Bookings_Group_Created extends Base {

	/**
	 * Get event ID.
	 *
	 * Returns the unique identifier for this event.
	 *
	 * @since 4.1.1
	 *
	 * @return string Event ID.
	 */
	public function get_id() {
		return 'bookings-group-created';
	}

	/**
	 * Get event name.
	 *
	 * Returns the human-readable name for this event.
	 *
	 * @since 4.1.1
	 *
	 * @return string Event name.
	 */
	public function get_name() {
		return __( 'Bookings Group Created (Multi Booking)', 'jet-booking' );
	}

	/**
	 * Get hook name.
	 *
	 * Returns the hook name for the bookings group creation event.
	 *
	 * @since 4.1.1
	 *
	 * @return string Hook name.
	 */
	public function get_hook() {
		return 'jet-booking/form-action/bookings-group-inserted';
	}

	/**
	 * Can dispatch.
	 *
	 * Determines if the event can be dispatched based on group bookings statuses.
	 *
	 * @since 4.1.1
	 *
	 * @param array $data    Additional data for the event.
	 * @param array $booking Bookings group data.
	 *
	 * @return bool
	 */
	public function can_dispatch( $data = [], $booking = [] ) {

		foreach ( $booking as $single_booking ) {
			if ( ! parent::can_dispatch( $data, $single_booking ) ) {
				return false;
			}
		}

		return true;

	}

	/**
	 * Dispatch.
	 *
	 * Dispatches actions for immediately-run group-created workflows only.
	 *
	 * @since 4.1.1
	 *
	 * @param array $data Additional data for the event.
	 *
	 * @return void
	 */
	public function dispatch( $data = [] ) {

		if ( empty( $data['actions'] ) || 'immediately' !== $data['schedule'] ) {
			return;
		}

		add_action( $this->get_hook(), function ( $bookings ) use ( $data ) {
			if ( ! $this->can_dispatch( $data, $bookings ) ) {
				return;
			}

			$actions = new Actions_Dispatcher( $data['actions'], $bookings );
			$actions->run();
		} );

	}

	/**
	 * Dispatches scheduled actions.
	 *
	 * Scheduled group-created workflows are intentionally unsupported because the
	 * workflow scheduler stores markers per booking, not per booking group.
	 *
	 * @since 4.1.1
	 *
	 * @param array $data Additional data for the event.
	 *
	 * @return void
	 */
	public function dispatch_scheduled( $data = [] ) {}

}
