<?php

namespace Uncanny_Automator\Integrations\Learndash;

/**
 * Class LD_TOPICDONE
 *
 * @property \Uncanny_Automator\Integrations\Learndash\Ld_Helpers $item_helpers
 *
 * @package Uncanny_Automator\Integrations\Learndash
 */
class LD_TOPICDONE extends \Uncanny_Automator\Recipe\Trigger {

	/**
	 * Static definition — opts the trigger into lazy loading.
	 *
	 * @return \Uncanny_Automator\Recipe\Trigger_Definition
	 */
	public static function definition() {
		return self::new_definition( 'LD_TOPICDONE', 'LD' )
			->trigger_meta( 'LDTOPIC' )
			->hook( 'learndash_topic_completed', 10, 1 );
	}

	/**
	 * Setup trigger.
	 *
	 * @return void
	 */
	protected function setup_trigger() {
		// integration / code / trigger_meta / trigger_type are auto-applied from definition().

		$this->set_sentence(
			sprintf(
				// translators: %1$s: Topic. %2$s: Number of times.
				esc_html_x( 'A user completes {{a topic:%1$s}} {{a number of:%2$s}} time(s)', 'LearnDash', 'uncanny-automator' ),
				$this->get_trigger_meta(),
				'NUMTIMES:' . $this->get_trigger_meta()
			)
		);

		$this->set_readable_sentence( esc_html_x( 'A user completes {{a topic}}', 'LearnDash', 'uncanny-automator' ) );
	}

	/**
	 * Trigger options — cascading course -> lesson -> topic select.
	 *
	 * @return array
	 */
	public function options() {

		return array(
			array(
				'option_code'     => 'LDCOURSE',
				'label'           => esc_html_x( 'Course', 'LearnDash', 'uncanny-automator' ),
				'input_type'      => 'select',
				'required'        => true,
				'options'         => array(),
				'relevant_tokens' => array(
					'LDCOURSE'           => esc_html_x( 'Course title', 'LearnDash', 'uncanny-automator' ),
					'LDCOURSE_ID'        => esc_html_x( 'Course ID', 'LearnDash', 'uncanny-automator' ),
					'LDCOURSE_URL'       => esc_html_x( 'Course URL', 'LearnDash', 'uncanny-automator' ),
					'LDCOURSE_THUMB_ID'  => esc_html_x( 'Course featured image ID', 'LearnDash', 'uncanny-automator' ),
					'LDCOURSE_THUMB_URL' => esc_html_x( 'Course featured image URL', 'LearnDash', 'uncanny-automator' ),
				),
				'remote_data'     => $this->item_helpers->remote_data_load_config( 'courses' ),
			),
			array(
				'option_code'     => 'LDLESSON',
				'label'           => esc_html_x( 'Lesson', 'LearnDash', 'uncanny-automator' ),
				'input_type'      => 'select',
				'required'        => true,
				'options'         => array(),
				'remote_data'     => $this->item_helpers->remote_data_parent_config( 'lessons_from_course', array( 'LDCOURSE' ) ),
				'relevant_tokens' => array(
					'LDLESSON'           => esc_html_x( 'Lesson title', 'LearnDash', 'uncanny-automator' ),
					'LDLESSON_ID'        => esc_html_x( 'Lesson ID', 'LearnDash', 'uncanny-automator' ),
					'LDLESSON_URL'       => esc_html_x( 'Lesson URL', 'LearnDash', 'uncanny-automator' ),
					'LDLESSON_THUMB_ID'  => esc_html_x( 'Lesson featured image ID', 'LearnDash', 'uncanny-automator' ),
					'LDLESSON_THUMB_URL' => esc_html_x( 'Lesson featured image URL', 'LearnDash', 'uncanny-automator' ),
				),
			),
			array(
				'option_code'     => 'LDTOPIC',
				'label'           => esc_html_x( 'Topic', 'LearnDash', 'uncanny-automator' ),
				'input_type'      => 'select',
				'required'        => true,
				'options'         => array(),
				'remote_data'     => $this->item_helpers->remote_data_parent_config( 'topics_from_lesson', array( 'LDLESSON' ) ),
				'relevant_tokens' => array(
					$this->get_trigger_meta()          => esc_html_x( 'Topic title', 'LearnDash', 'uncanny-automator' ),
					$this->get_trigger_meta() . '_ID'  => esc_html_x( 'Topic ID', 'LearnDash', 'uncanny-automator' ),
					$this->get_trigger_meta() . '_URL' => esc_html_x( 'Topic URL', 'LearnDash', 'uncanny-automator' ),
					$this->get_trigger_meta() . '_THUMB_ID' => esc_html_x( 'Topic featured image ID', 'LearnDash', 'uncanny-automator' ),
					$this->get_trigger_meta() . '_THUMB_URL' => esc_html_x( 'Topic featured image URL', 'LearnDash', 'uncanny-automator' ),
				),
			),
			Ld_Tokens_New_Framework::numtimes_field(),
		);
	}

	/**
	 * Define additional tokens for this trigger.
	 *
	 * @param array $trigger The trigger definition.
	 * @param array $tokens  Existing tokens.
	 *
	 * @return array
	 */
	public function define_tokens( $trigger, $tokens ) {

		$tokens_class = new Ld_Tokens_New_Framework();

		return array_merge(
			$tokens,
			$tokens_class->course_tokens(),
			$tokens_class->lesson_tokens(),
			$tokens_class->topic_tokens()
		);
	}

	/**
	 * Validate whether the trigger should fire.
	 *
	 * @param array $trigger   The trigger definition and metadata.
	 * @param array $hook_args The arguments from the WP hook.
	 *
	 * @return bool
	 */
	public function validate( $trigger, $hook_args ) {

		list( $data ) = $hook_args;

		if ( empty( $data ) ) {
			return false;
		}

		$user   = $data['user'] ?? null;
		$topic  = $data['topic'] ?? null;
		$lesson = $data['lesson'] ?? null;
		$course = $data['course'] ?? null;

		if ( empty( $user->ID ) || empty( $topic->ID ) ) {
			return false;
		}

		$this->set_user_id( $user->ID );

		$selected_course = $trigger['meta']['LDCOURSE'] ?? '';
		$selected_lesson = $trigger['meta']['LDLESSON'] ?? '';
		$selected_topic  = $trigger['meta'][ $this->get_trigger_meta() ] ?? '';
		$course_id       = absint( $course->ID ?? 0 );
		$lesson_id       = absint( $lesson->ID ?? 0 );
		$topic_id        = absint( $topic->ID ?? 0 );

		// Check course match.
		if ( intval( '-1' ) !== intval( $selected_course ) && absint( $selected_course ) !== $course_id ) {
			return false;
		}

		// Check lesson match.
		if ( intval( '-1' ) !== intval( $selected_lesson ) && absint( $selected_lesson ) !== $lesson_id ) {
			return false;
		}

		// Check topic match.
		if ( intval( '-1' ) !== intval( $selected_topic ) && absint( $selected_topic ) !== $topic_id ) {
			return false;
		}

		return true;
	}

	/**
	 * Hydrate tokens with actual values.
	 *
	 * @param array $trigger   The trigger definition.
	 * @param array $hook_args The arguments from the WP hook.
	 *
	 * @return array
	 */
	public function hydrate_tokens( $trigger, $hook_args ) {

		list( $data ) = $hook_args;

		$course_id = $data['course']->ID ?? 0;
		$lesson_id = $data['lesson']->ID ?? 0;
		$topic_id  = $data['topic']->ID ?? 0;
		$user_id   = $data['user']->ID ?? 0;

		$tokens_class = new Ld_Tokens_New_Framework();

		return array_merge(
			$tokens_class->hydrate_course_tokens( $course_id, $user_id ),
			$tokens_class->hydrate_lesson_tokens( $lesson_id ),
			$tokens_class->hydrate_topic_tokens( $topic_id ),
			array( $this->get_trigger_meta() => get_the_title( $topic_id ) )
		);
	}
}
