<?php

namespace EasyContentManager\Utils\Traits;

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

trait FieldGroups {


	public static function get_all_ecm_field_groups() {
		$args = [
			'post_type' => self::ECM_FIELD_GROUP_POST_TYPE_NAME,
			'posts_per_page' => -1,
		];

		return get_posts( $args );
	}

	public static function get_custom_field_group_from_post_type( string $given_post_type ) {
		$post_types = get_posts([
			'post_type'  => self::ECM_FIELD_GROUP_POST_TYPE_NAME,
			'posts_per_page' => -1,
			'post_status' => 'any',
		]);

		$field_groups = [];

		foreach ( $post_types as $post_type ) {
			$post_meta = maybe_unserialize( get_post_meta( $post_type->ID, 'ecm_field_group_location', true ) );

			if ( ! empty( $post_meta ) && in_array( $given_post_type, $post_meta, true ) ) {
				$field_groups[] = maybe_unserialize( $post_type->post_content );
			}
		}

		return $field_groups;
	}
	public static function get_all_custom_field_groups() {
		$posts = get_posts([
			'post_type' => self::ECM_FIELD_GROUP_POST_TYPE_NAME,
			'posts_per_page' => -1,
			'post_status' => 'any'
		]);

		return array_map(function ( $post ) {
			$content = maybe_unserialize( $post->post_content );
			$content['location'] = maybe_unserialize( get_post_meta( $post->ID, 'ecm_field_group_location', true ) ?? [] );
			return $content;
		}, $posts);
	}
}
