<?php
namespace AcademyProSuremembers;

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

use SureMembers\Inc\Traits\Get_Instance;
use SureMembers\Modules\Base_Module;

/**
 * Suremembers Integration
 *
 * @since 1.4.0
 */
class Integrations extends Base_Module {
	public function add_actions() {
		add_filter( 'suremembers_before_search_rules', array( $this, 'search_academy_course' ) );
	}
	public function add_rule_groups( $locations ) {
		if ( ! is_array( $locations ) ) {
			return $locations;
		}

		$locations['academy_lms'] = [
			'label' => __( 'Academy LMS', 'academy-pro' ),
			'value' => [
				'academy_courses|all' => __( 'Academy LMS Courses', 'academy-pro' ),
			],
		];

		return apply_filters( 'academy_lms_locations_in_suremembers_engine_rules', $locations );
	}
	public function exclude_post_types( $post_types, $context ) {
		if ( 'search' === $context ) {
			return $post_types;
		}
		if ( ! is_array( $post_types ) ) {
			return $post_types;
		}
		$post_types = array_merge( $post_types, [ 'academy_courses' ] );
		return $post_types;
	}
	public function search_academy_course( $rules ) {
		$replacements = [
			'academy-courses' => 'academy_courses||all',
		];

		$rules = \str_replace( array_keys( $replacements ), $replacements, $rules );
		return $rules;
	}
	public function add_access_group_data( $localizations ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( empty( $_GET['post_id'] ) ) {
			return $localizations;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$id = absint( $_GET['post_id'] );

		if ( empty( $id ) ) {
			return $localizations;
		}

		$post = get_post( $id );

		if ( empty( $post ) || SUREMEMBERS_POST_TYPE !== $post->post_type ) {
			return $localizations;
		}

		$includes = get_post_meta( $id, SUREMEMBERS_PLAN_INCLUDE, true );
		if ( empty( $includes ) || ! is_array( $includes ) ) {
			$includes = [];
		}
		$academy_courses_data = ! empty( $includes['academy_courses'] ) ? $includes['academy_courses'] : [];

		$localizations['academy_courses'] = $this->convert_to_slug( $academy_courses_data );

		return $localizations;
	}
	public function save_access_group_data( $include, $post_data ) {

		if ( ! empty( $post_data['academy_courses'] ) ) {
			$include['academy_courses'] = $post_data['academy_courses'];
			unset( $post_data['academy_courses'] );
		}

		return $include;
	}
}
