<?php
defined( 'ABSPATH' ) || exit; //Exit if accessed directly

/**
 * This class will assign a course to optin prospects if the Learndash plugin is installed and free course is setup to assign
 * Class WFFN_Optin_Action_Assign_LD_Course
 */
if ( ! class_exists( 'WFFN_Optin_Action_Assign_LD_Course' ) ) {
	#[AllowDynamicProperties]
	class WFFN_Optin_Action_Assign_LD_Course extends WFFN_Optin_Action {

		private static $slug = 'assign_ld_course';
		private static $ins = null;
		public $priority = 30;
		public $course_id = 0;

		/**
		 * WFFN_Optin_Action_Assign_LD_Course constructor.
		 */
		public function __construct() {
			parent::__construct();
			add_filter( 'learndash_post_args', array( $this, 'wffn_course_setting_fields' ) );
			add_action( 'template_redirect', array( $this, 'wffn_override_course_template' ) );
			add_filter( 'learndash_metabox_save_fields', array( $this, 'save_setting_for_classic_editor' ), 10, 1 );

		}

		/**
		 * @return WFFN_Optin_Action_Assign_LD_Course|null
		 */
		public static function get_instance() {
			if ( null === self::$ins ) {
				self::$ins = new self;
			}

			return self::$ins;
		}

		/**
		 * @return bool
		 */
		public function should_register() {
			if ( ! defined( 'LEARNDASH_VERSION' ) ) {
				return false;
			}

			return parent::should_register(); // TODO: Change the autogenerated stub
		}

		/**
		 * @return string
		 */
		public static function get_slug() {
			return self::$slug;
		}

		/**
		 * @param $posted_data
		 * @param $fields_settings
		 * @param $optin_action_settings
		 *
		 * @return array|bool|mixed
		 */
		public function handle_action( $posted_data, $fields_settings, $optin_action_settings ) {
			$posted_data = parent::handle_action( $posted_data, $fields_settings, $optin_action_settings );
			if ( false === $this->should_register() ) {
				return $posted_data;
			}

			$optin_page_id = filter_input( INPUT_POST, 'optin_page_id', FILTER_SANITIZE_NUMBER_INT );
			$optin_page_id = isset( $optin_page_id ) ? $optin_page_id : 0;

			if ( ! isset( $optin_action_settings['lms_course'] ) || 'false' === $optin_action_settings['lms_course'] ) {
				return $posted_data;
			}

			$courses = $optin_action_settings[ self::$slug ];

			if ( ! is_array( $courses ) || ! isset( $courses['id'] ) ) {
				return $posted_data;
			}

			$this->course_id = $courses['id'];
			if ( empty( $this->course_id ) ) {
				return $posted_data;
			}

			$posted_data = WFOPP_Core()->optin_actions->get_integration_object( 'create_wp_user' )->maybe_insert_user( $posted_data );
			$user_id     = isset( $posted_data['user_id'] ) ? $posted_data['user_id'] : 0;

			if ( ( $user_id <= 0 ) || ( $optin_page_id <= 0 ) ) {
				return $posted_data;
			}


			if ( ! is_array( $posted_data ) || count( $posted_data ) === 0 ) {
				return $posted_data;
			}

			add_filter( 'bwf_auto_login_redirect', function ( $url ) { //phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedParameter
				return get_permalink( $this->course_id );
			} );

			ld_update_course_access( $user_id, $this->course_id );

			WFFN_Core()->logger->log( 'LearnDash successfully course assign : user_id #' . $user_id . ', course_id #' . $this->course_id . ', optin_id' . $optin_page_id );

			return $posted_data;
		}


		/**
		 * @param $term
		 * search LD course
		 *
		 * @return array
		 */
		public function get_courses( $term ) {

			$result = [];

			if ( empty( $term ) ) {
				return $result;
			}

			$args = array(
				'post_type'      => 'sfwd-courses',
				'posts_per_page' => - 1,
				'post_status'    => 'publish',
				'orderby'        => 'title',
				'order'          => 'ASC',
			);

			if ( is_numeric( $term ) ) {
				$args['post__in'] = array( $term );
			} else {
				$args['s'] = $term;
			}

			$query_result = new WP_Query( apply_filters( 'wffn_listing_lms_query_args', $args ) );

			if ( $query_result instanceof WP_Query && $query_result->have_posts() ) {
				$result = $query_result->posts;

			}

			return $result;
		}

		/**
		 * Override course funnel step template.
		 * @return bool
		 */
		public function wffn_override_course_template() {

			if ( is_admin() ) {
				return false;
			}

			if ( ! is_singular( 'sfwd-courses' ) ) {
				return false;
			}

			$course_id = learndash_get_course_id();
			$user_id   = get_current_user_id();
			if ( is_user_logged_in() && sfwd_lms_has_access( $course_id, $user_id ) ) {
				return false;
			}

			if ( defined( 'LEARNDASH_VERSION' ) && version_compare( LEARNDASH_VERSION, '2.6.4', '>' ) ) { // phpcs:ignore WordPressVIPMinimum.Constants.ConstantString.NotCheckingConstantName

				$template = learndash_get_course_meta_setting( get_the_id(), 'wffn_course_template' );
			} else {

				$template = get_course_meta_setting( get_the_id(), 'wffn_course_template' );
			}

			if ( 'none' !== $template && $template ) {
				$link = get_permalink( $template );
				wp_safe_redirect( $link ); //phpcs:ignore WordPressVIPMinimum.Security.ExitAfterRedirect.NoExit
			}
		}

		/**
		 * Add settings inside learndash settings.
		 *
		 * @param $fields
		 *
		 * @return mixed
		 *
		 */
		public function wffn_course_setting_fields( $fields ) {
			if ( false === $this->should_register() ) {
				return $fields;
			}

			if ( isset( $_GET['post'] ) && $_GET['post'] !== '' && isset( $_GET['action'] ) && $_GET['action'] === 'edit' ) {//phpcs:ignore
				$post_type = get_post_type( $_GET['post'] ); //phpcs:ignore
				if ( $post_type === 'sfwd-courses' ) { //phpcs:ignore
					$all_posts = array(
						'none' => __( 'None', 'funnel-builder-powerpack' ),
					);

					$landing_steps = get_posts( array( //phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts
						'posts_per_page' => - 1,
						'post_type'      => array( 'wffn_landing', 'wffn_optin', 'wfacp_checkout' ),
						'post_status'    => 'publish',
						'orderby'        => 'ID',
						'order'          => 'DESC',
					) );

					foreach ( $landing_steps as $landing_step ) {
						$all_posts[ $landing_step->ID ] = get_the_title( $landing_step->ID ) . ' ( #' . $landing_step->ID . ')';
					}

					$description = sprintf( __( 'Non-enrolled students will redirect to the selected Funnel template. If you have not created any Funnel already, add new Funnel from %1$shere%2$s.', 'funnel-builder-powerpack' ), '<a href="' . esc_url( admin_url( 'admin.php?page=bwf_funnels' ) ) . '">', '</a>' );

					$fields['sfwd-courses']['fields']['wffn_course_template'] = array(
						'name'            => __( 'Select Funnel step for this Course', 'funnel-builder-powerpack' ),
						'type'            => 'select',
						'initial_options' => $all_posts,
						'default'         => 'none',
						'help_text'       => $description,
						'show_in_rest'    => true,
						'rest_args'       => array(
							'schema' => array(
								'type' => 'string',
							),
						),
					);
				}
			}

			return $fields;
		}

		/**
		 * Save setting in classic editor
		 *
		 * @param $settings_field_updates
		 *
		 * @return mixed
		 */
		public function save_setting_for_classic_editor( $settings_field_updates ) {
			if ( isset( $_POST['sfwd-courses_wffn_course_template'] ) ) {
				$settings_field_updates['wffn_course_template'] = $_POST['sfwd-courses_wffn_course_template'];
			}

			return $settings_field_updates;
		}
	}

	if ( class_exists( 'WFOPP_Core' ) ) {
		WFOPP_Core()->optin_actions->register( WFFN_Optin_Action_Assign_LD_Course::get_instance() );
	}
}
