<?php
namespace AcademyProFluentCRM\DeepIntegration;

use AcademyProFluentCRM\Helper;

class AutomationConditions {

	public function init() {
		add_filter( 'fluentcrm_automation_condition_groups', array( $this, 'add_automation_conditions' ), 10, 1 );
		add_filter('fluentcrm_automation_conditions_assess_academylms', array( $this, 'assess_automation_conditions' ), 10,
		3);
		add_filter( 'fluentcrm_ajax_options_product_selector_academylms', array( $this, 'get_courses' ), 10, 1 );
	}

	public function add_automation_conditions( $groups ) {
		$groups['academylms'] = [
			'label'    => __( 'Academy LMS', 'academy-pro' ),
			'value'    => 'academylms',
			'children' => [
				[
					'value'             => 'is_in_course',
					'label'             => __( 'Course Enrollment', 'academy-pro' ),
					'type'              => 'selections',
					'component'         => 'product_selector',
					'is_multiple'       => true,
					'is_singular_value' => true
				],
				[
					'value'             => 'is_course_completed',
					'label'             => __( 'Course Completed', 'academy-pro' ),
					'type'              => 'selections',
					'component'         => 'product_selector',
					'is_multiple'       => true,
					'is_singular_value' => true
				],
			],
		];
		return $groups;
	}

	public function assess_automation_conditions( $result, $conditions, $subscriber ) {
		foreach ( $conditions as $condition ) {
			$operator = $condition['operator'];
			$courses = $condition['data_value'];
			$datKey = $condition['data_key'];

			if ( 'is_in_course' === $datKey ) {
				$isInCourse = Helper::is_in_courses( $courses, $subscriber );
				if ( ( 'in' === $operator && ! $isInCourse ) || ( $isInCourse && 'not_in' === $operator ) ) {
					return false;
				}
			} elseif ( 'is_course_completed' === $datKey ) {
				$isComplete = Helper::is_courses_completed( $courses, $subscriber );
				if ( ( 'in' === $operator && ! $isComplete ) || ( $isComplete && 'not_in' === $operator ) ) {
					return false;
				}
			}
		}

		return $result;
	}

	public function get_courses( $memberships ): array {
		return Helper::get_courses();
	}
}
