<?php
namespace AcademyProBuddypress;

use ActivityRegistration;


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class Configaration {

	public static function init() : void {

		$instance = new self();

		$instance->add_settings_to_rest();

		add_action(
			'wp_ajax_academy_pro/buddypress/groups',
			[ $instance, 'get_groups' ]
		);
	}

	public function add_settings_to_rest() : void {
		register_post_meta('academy_courses', 'is_buddypress_notification_active', [
			'type' => 'boolean',
			'description' => 'Notification status.',
			'single' => true,
			'show_in_rest' => true,
			'default' => true,

			'auth_callback' => function() {
				return current_user_can( 'manage_options' );
			}
		]);
		register_post_meta('academy_courses', 'assigned_buddypress_groups', [
			'type' => 'array',
			'description' => 'Buddypress group id array.',
			'single' => true,
			'show_in_rest' => [
				'schema' => [
					'type' => 'array',
					'items' => [
						'type' => 'integer',
					],
					'description' => 'Buddypress group ID',
				],
			],

			'auth_callback' => function() {
				return current_user_can( 'manage_options' );
			}
		]);
	}

	public function get_groups(): void {
		check_ajax_referer( 'academy_nonce', 'security' );

		if ( ! current_user_can( 'edit_academy_course' ) ) {
			wp_send_json_error([
				'message' => __( 'Unauthorized.', 'academy-pro' )
			], 401);
		}

		if ( function_exists( 'groups_get_groups' ) ) {
			wp_send_json_success( groups_get_groups() );
		}

		wp_send_json_error([
			'message' => __( 'Error', 'academy-pro' )
		], 500);
	}
}
