<?php

namespace JET_ABAF\Formbuilder_Plugin\Generators;

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

trait Booking_Statuses_Generator_Trait {

	/**
	 * Get status groups as select options.
	 *
	 * @return array
	 */
	private function get_status_groups_for_select(): array {
		$options = array();

		if ( ! function_exists( 'jet_abaf' ) ) {
			return $options;
		}

		$schema = jet_abaf()->statuses->get_schema();

		foreach ( array_keys( $schema ) as $group ) {
			$options[] = array(
				'value' => $group,
				'label' => ucwords( str_replace( '_', ' ', $group ) ),
			);
		}

		return $options;
	}

	/**
	 * Normalize generator input into an array of status groups.
	 *
	 * @param mixed $args Generator args (array|string in V2, legacy array in Base).
	 *
	 * @return array
	 */
	private function normalize_groups_from_args( $args ): array {
		if ( is_array( $args ) && array_key_exists( 'generator_field', $args ) && count( $args ) === 1 ) {
			$args = $args['generator_field'];
		}

		if ( is_string( $args ) ) {
			$groups = explode( '|', $args );
		} elseif ( is_array( $args ) ) {
			$status_group = $args['status_group'] ?? array();

			if ( is_string( $status_group ) ) {
				$groups = explode( '|', $status_group );
			} elseif ( is_array( $status_group ) ) {
				$groups = $status_group;
			} else {
				$groups = array();
			}

			if ( empty( $groups ) && ! empty( $args['generator_field'] ) ) {
				$groups = explode( '|', $args['generator_field'] );
			}
		} else {
			$groups = array();
		}

		$groups = array_map( 'strval', $groups );
		$groups = array_filter( $groups, static fn( $v ) => '' !== trim( $v ) );

		return array_values( $groups );
	}

	/**
	 * Build booking statuses options by groups.
	 *
	 * @param array $groups Status groups list.
	 *
	 * @return array
	 */
	private function build_options_by_groups( array $groups ): array {
		if ( ! function_exists( 'jet_abaf' ) ) {
			return array();
		}

		$statuses = jet_abaf()->statuses->get_statuses();
		$result   = array();

		// No group filter — return all statuses.
		if ( empty( $groups ) ) {
			foreach ( $statuses as $key => $label ) {
				$result[] = array(
					'value' => $key,
					'label' => $label,
				);
			}

			return $result;
		}

		// Collect statuses from all selected groups, preserving order, no duplicates.
		$statuses_schema = jet_abaf()->statuses->get_schema();
		$seen            = array();

		foreach ( $groups as $group ) {
			if ( ! isset( $statuses_schema[ $group ] ) ) {
				continue;
			}

			foreach ( $statuses_schema[ $group ] as $status ) {
				if ( isset( $statuses[ $status ] ) && ! isset( $seen[ $status ] ) ) {
					$seen[ $status ] = true;
					$result[]        = array(
						'value' => $status,
						'label' => $statuses[ $status ],
					);
				}
			}
		}

		return $result;
	}

	/**
	 * Check if generator can generate options.
	 *
	 * @return bool
	 */
	public function can_generate() {
		return function_exists( 'jet_abaf' );
	}
}

if ( class_exists( '\\Jet_Form_Builder\\Generators\\Base_V2' ) ) {
	class Get_From_Booking_Statuses extends \Jet_Form_Builder\Generators\Base_V2 {
		use Booking_Statuses_Generator_Trait;

		/**
		 * Returns generator ID.
		 *
		 * @since 3.3.0
		 *
		 * @return string
		 */
		public function get_id() {
			return 'get_from_booking_statuses';
		}

		/**
		 * Returns generator name.
		 *
		 * @since 3.3.0
		 *
		 * @return string
		 */
		public function get_name() {
			return __( 'Get values list from booking statuses', 'jet-booking' );
		}

		/**
		 * Returns structured settings schema.
		 *
		 * @return array
		 */
		public function get_settings_schema(): array {
			return array(
				'status_group' => array(
					'type'     => 'array',
					'default'  => array(),
					'label'    => __( 'Status Groups', 'jet-booking' ),
					'control'  => 'select',
					'multiple' => true,
					'options'  => $this->get_status_groups_for_select(),
					'help'     => __( 'Filter statuses by group. Leave empty to show all statuses.', 'jet-booking' ),
				),
			);
		}

		/**
		 * Enrich legacy generator_field (pipe-delimited groups) into structured format.
		 *
		 * @param string $generator_field Legacy pipe string.
		 * @param array  $block_attrs     All block attributes.
		 *
		 * @return array
		 */
		protected function enrich_legacy_field( string $generator_field, array $block_attrs ) {
			$parts = array_filter( explode( '|', $generator_field ), static fn( $v ) => '' !== $v );

			return array(
				'status_group' => array_values( $parts ),
			);
		}

		/**
		 * Returns generated options list.
		 *
		 * @since 3.3.0
		 *
		 * @param array|string $args Settings array or legacy pipe-delimited string.
		 *
		 * @return array
		 */
		public function generate( $args ) {
			$groups = $this->normalize_groups_from_args( $args );

			return $this->build_options_by_groups( $groups );
		}
	}
} elseif ( class_exists( '\\Jet_Form_Builder\\Generators\\Base' ) ) {
	class Get_From_Booking_Statuses extends \Jet_Form_Builder\Generators\Base {
		use Booking_Statuses_Generator_Trait;

		/**
		 * Returns generator ID.
		 *
		 * @return string
		 */
		public function get_id() {
			return 'get_from_booking_statuses';
		}

		/**
		 * Returns generator name.
		 *
		 * @return string
		 */
		public function get_name() {
			return __( 'Get values list from booking statuses', 'jet-booking' );
		}

		/**
		 * Legacy generator attributes parser.
		 *
		 * @return array
		 */
		public function incoming_args() {
			return array(
				'generator_field' => static function ( $value ) {
					return $value;
				},
			);
		}

		/**
		 * Returns generated options list.
		 *
		 * @param mixed $args Legacy generator args.
		 *
		 * @return array
		 */
		public function generate( $args ) {
			$groups = $this->normalize_groups_from_args( $args );

			return $this->build_options_by_groups( $groups );
		}
	}
}
