<?php
namespace AcademyProBuddyboss\Activities;

use AcademyProBuddyboss\ActivityRegistration;
use AcademyProBuddyboss\Helpers\Activity;

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

class CourseActivity {


	public static function init(): void {
		$instance = new self();

		/** Track New enrollment Activity */
		add_action(
			'academy/course/after_enroll',
			[ $instance, 'new_enrollment' ],
			10, 3
		);

		/** Track Course compled Activity */
		add_action(
			'academy/admin/course_complete_after',
			[ $instance, 'course_complete' ],
			10, 2
		);

	}

	public function new_enrollment( int $course_id, int $enroll_id, int $user_id ): 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 );
		$user = get_userdata( $user_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(
			'Please join us in welcoming %s, who has just enrolled in the <a href="%s">%s</a>! 🎉 We\'re excited to have you on board. Get ready to dive into some amazing content and start your learning journey. Let\'s make this an awesome experience together!',
			esc_html( $user ? $user->display_name : '' ),
			esc_url( $course_permalink ),
			esc_html( $course_title )
		);

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

		$activity->post();
	}

	public function course_complete( $course_id, $user_id ) {
		$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 );
		$user = get_userdata( $user_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>🎉 Congratulations on completing the <a href="%s">%s</a>, %s! 🎉</h3><p>You\'ve worked hard, and we\'re so proud of your achievement! 🚀</p>',
			esc_url( $course_permalink ),
			esc_html( $course_title ),
			esc_html( $user ? $user->display_name : '' )
		);

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

		$activity->post();
	}

}
