<?php
namespace AcademyProBuddyboss\Activities;

use stdClass;
use AcademyProBuddyboss\ActivityRegistration;
use AcademyProBuddyboss\Helpers\Activity;
use AcademyProBuddyboss\Helpers\TrackCurriculumChanges;


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


class QuizActivity {

	public static function init(): void {

		$instance = new self();

		/** Tracking quiz attempt activity */
		add_action(
			'academy_quizzes/api/after_quiz_attempt_start',
			[ $instance, 'quiz_start' ],
			999, 3
		);
		/** Tracking quiz finish activity */
		add_action(
			'academy_quizzes/api/after_quiz_attempt_finished',
			[ $instance, 'quiz_end' ],
			999, 3
		);
	}


	public function quiz_start( stdClass $quiz ): void {
		$groups = ActivityRegistration::get_assigned_groups( $quiz->course_id );
		if (
			empty( $quiz->course_id ) ||
			empty( $quiz->user_id ) ||
			empty( $groups )
		) {
			return;
		}

		$course_permalink = get_permalink( $quiz->course_id );
		$course_title = get_the_title( $quiz->course_id );

		$data = [];
		$user = get_userdata( $quiz->user_id );
		$data['user_id']   = $quiz->user_id;
		$data['course_id'] = $quiz->course_id;
		$data['action'] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( $course_permalink ),
			wp_strip_all_tags( $course_title )
		);

		$data['content'] = sprintf(
			'<p>%s is attempting to solve the <a href="%s">quiz</a> at %s. Now, it\'s your turn to give it a try!</p>',
			wp_strip_all_tags( $user ? $user->display_name : '' ),
			esc_url( $course_permalink ),
			wp_strip_all_tags( $course_title )
		);

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

		$activity->post();

	}


	public function quiz_end( stdClass $quiz ): void {
		$groups = ActivityRegistration::get_assigned_groups( $quiz->course_id );
		if (
			empty( $quiz->course_id ) ||
			empty( $quiz->user_id ) ||
			empty( $groups )
		) {
			return;
		}

		$course_permalink = get_permalink( $quiz->course_id );
		$course_title = get_the_title( $quiz->course_id );

		$data = [];
		$user = get_userdata( $quiz->user_id );
		$data['user_id']   = $quiz->user_id;
		$data['course_id'] = $quiz->course_id;
		$data['action'] = sprintf(
			'<a href="%s">%s</a>',
			esc_url( $course_permalink ),
			wp_strip_all_tags( $course_title )
		);

		$data['content'] = sprintf(
			'<p>%s solved a <a href="%s">quiz</a> at %s. Now, it\'s your turn to give it a try!</p>',
			wp_strip_all_tags( $user ? $user->display_name : '' ),
			esc_url( $course_permalink ),
			wp_strip_all_tags( $course_title )
		);

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

		$activity->post();

	}
}
