<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Implementas groups of optional packages available for wiaas standard package type
 *
 * Class Wiaas_Package_Option_Groups
 */
class Wiaas_Package_Option_Groups {

	public static function init() {

		add_filter('wiaas_package_types', array( __CLASS__, 'register_option_package_type' ) );
	}

	/**
	 * Register option as ne of available wiaas package types
	 * @param $package_types
	 *
	 * @return array
	 */
	public static function register_option_package_type($package_types) {
		$package_types[] = 'option';

		return $package_types;
	}

	/**
	 * Retrives options group name for package option
	 * @param $package
	 * @param $option_package
	 *
	 * @return string|null
	 */
	public static function get_group_name_for_package_option($package, $option_package) {
		$option_groups = $package->get_meta( '_wiaas_package_option_groups' );

		foreach ($option_groups as $option_group) {
			foreach ($option_group['options'] as $group_option_id) {
				if ((int) $group_option_id === $option_package->get_id()) {
					return $option_group['name'];
				}
			}
		}

		return null;
	}

	/**
	 * Retrieve groups of optional packages configured for provided package
	 * @param $package
	 *
	 * @return array
	 */
	public static function get_package_option_groups($package) {

		$groups_data = $package->get_meta( '_wiaas_package_option_groups' );

		$option_groups =  array();

		foreach ($groups_data as $group_data) {
			$group = array(
				'id' => $group_data['id'],
				'name' => $group_data['name'],
				'default' => $group_data['default'],
				'options' => array()
			);

			foreach ($group_data['options'] as $option_id) {
				$option_package = wc_get_product( $option_id );
				if (is_object($option_package)) {
					$group['options'][] = $option_package;
				}
			}
			$option_groups[] = $group;
		}

		return $option_groups;
	}

	/**
	 * Retrieve ids of all package options
	 * @param int $package
	 *
	 * @return array
	 */
	public static function get_package_option_ids($package) {
		$groups_data = $package->get_meta( '_wiaas_package_option_groups' );

		$options_ids = array();

		foreach ($groups_data as $group_data) {
			$options_ids = array_merge($options_ids, $group_data['options']);
		}

		return array_unique($options_ids);
	}

	/**
	 * Set groups of optional packages for provided package
	 * @param $package
	 * @param $groups_data
	 */
	public static function set_package_option_groups($package, $groups_data) {
		$package->update_meta_data( '_wiaas_package_option_groups', $groups_data );
		$package->save_meta_data();
	}
}

Wiaas_Package_Option_Groups::init();