<?php
namespace AcademyProBuddypress\Activities;

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


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


class LessonActivity {

	public static function init(): void {

		$instance = new self();

		/** Tracking lession & quiz update at course */
		add_action(
			'rest_insert_academy_courses',
			[ $instance, 'notify' ],
			999, 3
		);
	}

	public function notify( $post, $request, $creating ) :void {

		$course_id_array = $request->get_params();

		$old_data = get_post_meta( $post->ID, 'academy_course_curriculum', true );

		$course_curriculum = $course_id_array['meta']['academy_course_curriculum'] ?? [];

		if (
			! is_array( $old_data ) ||
			! is_array( $course_curriculum )
		) {
			return;
		}

		$this->lesson_update(
			$post->ID,
			$post->post_author,
			( new TrackCurriculumChanges( (array) $old_data, (array) $course_curriculum ) )->get_changes()
		);

	}

	public function lesson_update( int $course_id, int $author_id, array $changes ): void {
		$groups = ActivityRegistration::get_assigned_groups( $course_id );
		if (
			empty( $course_id ) ||
			empty( $author_id ) ||
			empty( $changes ) ||
			empty( $groups )
		) {
			return;
		}

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

		$data = [];

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

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

		$content = '';
		if ( array_key_exists( 'new', $changes ) ) {
			$content .= '<h4>Following Lessons is  added at ' . $data['action'] . '</h4>';
			$content .= '<ul>';
			foreach ( $changes['new'] as $lession ) {
				$content .= sprintf(
					'<li><strong><mark>%s: %s</mark></strong> <i>from %s</i></li>',
					strtoupper( wp_strip_all_tags( $lession['type'] ) ),
					strtoupper( wp_strip_all_tags( $lession['name'] ) ),
					strtoupper( wp_strip_all_tags( $changes['curriculums'][ $lession['slug'] ] ?? $lession['slug'] ) ),
				);
			}
			$content .= '</ul>';
		}

		if ( array_key_exists( 'updated', $changes ) ) {
			$content .= '<h4>Following Lessons is removed/updated at ' . $data['action'] . '</h4>';
			$content .= '<ul>';
			foreach ( $changes['updated'] as $lession ) {
				$content .= sprintf(
					'<li><strong><mark>%s: %s</mark></strong> <i>from %s</i></li>',
					strtoupper( wp_strip_all_tags( $lession['type'] ) ),
					strtoupper( wp_strip_all_tags( $lession['name'] ) ),
					strtoupper( wp_strip_all_tags( $changes['curriculums'][ $lession['slug'] ] ?? $lession['slug'] ) ),
				);
			}
			$content .= '</ul>';
		}

		$data['content'] = wp_kses_post( $content );

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

		$activity->post();

	}
}
