<?php

namespace AcademyProBuddypress\Helpers;

use AcademyProBuddypress\ActivityRegistration;

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


class Activity {

	protected string $event;
	protected array $args;
	protected array $activity_settings;
	protected array $groups;
	protected string $settings_key = 'buddypress_group_activities';


	public function __construct( array $groups, string $event, array $args ) {

		$this->groups = $groups;
		$this->event = $event;
		$this->args   = $args;

		foreach ( $this->groups as $id ) {

			$data = groups_get_groupmeta( $id, $this->settings_key );

			if ( empty( $data ) ) {
				continue;
			}

			foreach ( $data as $key ) {
				$this->activity_settings[ $key ][] = $id;
			}
		}

	}


	public function post() : void {
		foreach ( $this->activity_settings[ $this->event ] ?? [] as $id ) {
			$this->post_( $id );
		}
	}


	protected function post_( int $group_id ) : void {
		$data = [];
		$data['item_id'] = $group_id;
		$data['component'] = 'groups';
		$data['type'] = 'activity_update';

		// skip if notification is deactivated for this course
		if (
			! ActivityRegistration::get_status( $this->args['course_id'] ?? 0 )
		) {
			return;
		}

		if ( isset( $this->args['user_id'] ) ) {
			$data['user_id'] = $this->args['user_id'];

			if ( ! groups_is_user_member( $data['user_id'], $group_id ) ) {
				groups_join_group( $group_id, $data['user_id'] );
			}
		}

		if ( isset( $this->args['action'] ) ) {
			$data['action'] = $this->args['action'];
		}

		if ( isset( $this->args['content'] ) ) {
			$data['content'] = $this->args['content'];
		}

		bp_activity_add( $data );
	}
}
