<?php
namespace AcademyProBuddypress\Activities;

use AcademyProBuddypress\ActivityRegistration;
use AcademyProBuddypress\Helpers\Activity;

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


class AnnouncementsActivity {

	public static function init(): void {

		$instance = new self();

		/** Track new Announcement  */
		add_action(
			'rest_insert_academy_announcement',
			[ $instance, 'notify' ],
			400000, 3
		);

	}

	public function notify( $post, $request, $creating ) {
		$course_id_array = $request->get_params();

		if ( $creating ) {
			$course_id_array = $course_id_array['meta']['academy_announcements_course_ids'] ?? [];

			foreach ( $course_id_array as $course ) {
				$this->course_announcements(
					$course['value'],
					get_current_user_id(),
					apply_filters( 'the_content', $post->post_content )
				);
			}
		}
	}

	public function course_announcements( int $course_id, int $user_id, string $text = null ): void {
		$groups = ActivityRegistration::get_assigned_groups( $course_id );
		if (
			empty( $user_id ) ||
			empty( $groups )
		) {
			return;
		}

		$course_permalink = get_permalink( $course_id );
		$course_title = get_the_title( $course_id );

		$data = [];
		$data['user_id']   = $user_id;
		$data['course_id'] = $course_id;

		$data['action'] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( $course_permalink ),
			esc_html( $course_title )
		);

		$data['content'] = sprintf(
			'<h3><a href="%s"> IMPORTANT ANNOUNCEMENT @%s </a></h3>
            <p>%s</p>',
			esc_url( $course_permalink ),
			esc_html( $course_title ),
			wp_strip_all_tags( $text )
		);

		$activity = new Activity( $groups, 'course_announcements', $data );

		$activity->post();

	}

}
