<?php
/**
 * Extend Group Endpoints
 *
 * @package Nisje
 */

defined( 'ABSPATH' ) || die( 'Shame on you' );

// Types to extend.
$post_types = apply_filters( 'nisje_rest_shared_fields_group_post_types', [] );

if ( empty( $post_types ) || ! is_array( $post_types ) ) {
	return;
}

// Group ID.
register_rest_field( $post_types, 'group_id', [
	'get_callback' => function( $object ) {
		$group_id = (int) get_post_meta( $object['id'], '_nisje_group_connection', true );
		if ( ! $group_id ) {
			$group_id = 0;
		}

		return (int) $group_id;
	},
	'schema'       => [
		'context'     => [ 'view', 'edit' ],
		'description' => esc_html__( 'Group ID', 'nisje' ),
		'type'        => 'integer',
		'readonly'    => true,
	],
] );

// Group Name.
register_rest_field( $post_types, 'group_name', [
	'get_callback' => function( $object ) {
		$group_name = '';

		$group_id = (int) get_post_meta( $object['id'], '_nisje_group_connection', true );

		if ( $group_id ) {
			$group = nisje_get_group( $group_id );
			if ( ! is_wp_error( $group ) ) {
				$group_name = bp_get_group_name( $group );
			}
		}

		return $group_name;
	},
	'schema'       => [
		'context'     => [ 'view', 'edit' ],
		'description' => esc_html__( 'Group Name', 'nisje' ),
		'type'        => 'string',
		'readonly'    => true,
	],
] );
