<?php
// phpcs:ignoreFile
namespace AcademyProFluentCRM\Actions;

use AcademyProFluentCRM\Helper;
use FluentCrm\App\Services\Funnel\BaseAction;
use FluentCrm\App\Services\Funnel\FunnelHelper;
use FluentCrm\Framework\Support\Arr;

class RemoveFromCourseAction extends BaseAction {
	public function __construct() {
		$this->actionName = 'academy_lms_remove_from_course';
		$this->priority   = 20;
		parent::__construct();
	}

	public function getBlock() {
		return [
			'category'    => __( 'Academy LMS', 'academy-pro' ),
			'title'       => __( 'Remove From a Course', 'academy-pro' ),
			'description' => __( 'Remove the contact from a specific LMS Course', 'academy-pro' ),
			'icon'        => 'dashicons dashicons-welcome-learn-more',
			'settings'    => [
				'course_id' => ''
			]
		];
	}

	public function getBlockFields() {
		return [
			'title'     => __( 'Remove From a Course', 'academy-pro' ),
			'sub_title' => __( 'Remove the contact from a specific LMS Course', 'academy-pro' ),
			'fields'    => [
				'course_id' => [
					'type'        => 'select',
					'option_key'  => 'product_selector_academy_lms',
					'options'     => Helper::get_courses(),
					'is_multiple' => false,
					'clearable'   => true,
					'label'       => __( 'Select a course that you want to remove from', 'academy-pro' ),
					'placeholder' => __( 'Select Course', 'academy-pro' )
				]
			]
		];
	}

	public function handle( $subscriber, $sequence, $funnelSubscriberId, $funnelMetric ): bool {
		$settings = $sequence->settings;
		$userId   = $subscriber->getWpUserId();

		$courseId = Arr::get( $settings, 'course_id' );

		if ( ! $userId ) {
			$funnelMetric->notes = __( 'Funnel Skipped because user could not be found', 'academy-pro' );
			$funnelMetric->save();
			FunnelHelper::changeFunnelSubSequenceStatus( $funnelSubscriberId, $sequence->id, 'skipped' );

			return false;
		}

		$result = \AcademyProEnrollment\Helper::cancel_enroll( $courseId, $userId );

		if ( ! $result ) {
			$funnelMetric->notes = __( 'User is not enrolled in the course', 'academy-pro' );
			$funnelMetric->save();
			FunnelHelper::changeFunnelSubSequenceStatus( $funnelSubscriberId, $sequence->id, 'skipped' );
		}
		return true;
	}
}
