<?php
namespace AcademyProFluentCommunity;

use ActivityRegistration;
use FluentCommunity\App\Functions\Utility;

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


class Setting {

	protected array $allowed_events = [
		'course_enrollment',
		// 'course_start',
		'course_complete',
		'course_announcements',
		'user_question',
		'question_answer',
		'lesson_update',
		'quiz_start',
		'quiz_end',
	];

	public static function init() : void {

		$instance = new self();

		$instance->add_settings_to_rest();

		add_action(
			'wp_ajax_academy_pro/fluent_community/spaces',
			[ $instance, 'get_spaces' ]
		);
	}

	public function add_settings_to_rest() : void {
		register_post_meta('academy_courses', 'is_fluent_community_feed_active', [
			'type' => 'boolean',
			'description' => __( 'Fluent Community feed status.', 'academy-pro' ),
			'single' => true,
			'show_in_rest' => true,
			'default' => true,

			'auth_callback' => function() {
				return current_user_can( 'manage_options' );
			}
		]);
		register_post_meta('academy_courses', 'fluent_community_notifiable_events', [
			'type' => 'array',
			'description' => __( 'Allowed Events for push feed at Fluent Community.', 'academy-pro' ),
			'single' => true,
			'show_in_rest' => [
				'schema' => [
					'type' => 'array',
					'items' => [
						'type' => 'string',
						'enum' => $this->allowed_events,
					],
					'description' => __( 'Academy Event', 'academy-pro' ),
				],
			],

			'auth_callback' => function() {
				return current_user_can( 'manage_options' );
			}
		]);
		register_post_meta('academy_courses', 'fluent_community_space_id', [
			'type' => 'integer',
			'description' => __( 'Fluent Community Space ID.', 'academy-pro' ),
			'single' => true,
			'show_in_rest' => true,
			'default' => 0,

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

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

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

		if ( method_exists( Utility::class, 'getSpaces' ) ) {
			wp_send_json_success( Utility::getSpaces( false ) );
		}

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