<?php
/**
 * New Course Announcement webhook event listener class.
 *
 * @since 2.8.3
 */

namespace Masteriyo\Addons\CourseAnnouncement\Listener;

use Masteriyo\Abstracts\Listener;
use Masteriyo\Addons\CourseAnnouncement\Resources\CourseAnnouncementResource;
use Masteriyo\Resources\WebhookResource;

defined( 'ABSPATH' ) || exit;

/**
 * New Course Announcement webhook event listener class.
 *
 * @since 2.8.3
 */
class NewCourseAnnouncementListener extends Listener {

	/**
	 * Event name the listener is listening to.
	 *
	 * @since 2.8.3
	 */
	protected $event_name = 'announcement.created';

	/**
	 * Get event label.
	 *
	 * @since 2.8.3
	 *
	 * @return string
	 */
	public function get_label() {
		return __( 'New Course Announcement', 'learning-management-system' );
	}

	/**
	 * Setup the webhook event.
	 *
	 * @since 2.8.3
	 *
	 * @param callable $deliver_callback
	 * @param \Masteriyo\Models\Webhook $webhook
	 */
	public function setup( $deliver_callback, $webhook ) {
		add_action(
			'masteriyo_new_course_announcement',
			function( $id, $course_announcement ) use ( $deliver_callback, $webhook ) {
				if ( ! $this->can_deliver( $webhook, $course_announcement->get_id() ) ) {
					return;
				}

				call_user_func_array(
					$deliver_callback,
					array(
						WebhookResource::to_array( $webhook ),
						$this->get_payload( $course_announcement, $webhook ),
					)
				);
			},
			10,
			2
		);
	}

	/**
	 * Get payload data for the currently triggered webhook.
	 *
	 * @since 2.8.3
	 *
	 * @param \Masteriyo\Addons\CourseAnnouncement\Models\CourseAnnouncement $course_announcement
	 * @param \Masteriyo\Models\Webhook $webhook
	 *
	 * @return array
	 */
	protected function get_payload( $course_announcement, $webhook ) {
		$data = CourseAnnouncementResource::to_array( $course_announcement );

		/**
		 * Filters the payload data for the currently triggered webhook.
		 *
		 * @since 2.8.3
		 *
		 * @param array $data The payload data.
		 * @param \Masteriyo\Models\Webhook $webhook
		 */
		return apply_filters( "masteriyo_webhook_payload_for_{$this->event_name}", $data, $webhook );
	}
}
