<?php

namespace AcademyProFluentCommunity\Classes;

use FluentCommunity\App\Services\{ FeedsHelper, Helper };

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

class PushFeed {

	protected int $course_id;
	protected string $title;
	protected string $msg;
	protected string $event;

	protected int $space_id;
	protected bool $is_feed_activated;
	protected int $user_id;
	protected array $allowed_events;

	public function __construct( int $course_id, string $title, string $msg, string $event ) {
		$this->course_id = $course_id;
		$this->title = $title;
		$this->msg   = $msg;
		$this->event = $event;

		$this->user_id        = (int) get_current_user_id();
		$this->allowed_events = (array) get_post_meta( $this->course_id, 'fluent_community_notifiable_events', true );
		$this->is_feed_activated  = (bool) get_post_meta( $this->course_id, 'is_fluent_community_feed_active', true );
		$this->space_id  = (int) get_post_meta( $this->course_id, 'fluent_community_space_id', true );
	}

	public function post() : void {
		if ( $this->is_activated() && $this->is_event_allowed() ) {
			if ( ! $this->is_user_in_space() ) {
				$this->add_user_to_space();
			}

			FeedsHelper::createFeed( [
				'title'   => $this->title,
				'message' => $this->msg,
				'space_id' => $this->space_id,
				'user_id'  => $this->user_id,
			] );
		}
	}

	protected function is_activated() : bool {
		return $this->is_feed_activated;
	}

	protected function is_event_allowed() : bool {
		return in_array( $this->event, $this->allowed_events, true );
	}
	protected function is_user_in_space() : bool {
		return in_array( $this->space_id, (array) Helper::getUserSpaceIds( $this->user_id ) );
	}
	protected function add_user_to_space() : void {
		Helper::addToSpace( $this->space_id, $this->user_id, 'member', 'by_admin' );
	}
}
