<?php

namespace AcademyProFluentCRM;

use Academy\Helper;
use AcademyProFluentCRM\Actions\AddToCourseAction;
use AcademyProFluentCRM\Actions\RemoveFromCourseAction;
use AcademyProFluentCRM\DeepIntegration\AcademyImporter;
use AcademyProFluentCRM\DeepIntegration\AutomationConditions;
use AcademyProFluentCRM\DeepIntegration\DeepIntegration;
use AcademyProFluentCRM\Triggers\CourseCompletedTrigger;
use AcademyProFluentCRM\Triggers\CourseEnrollTrigger;
use AcademyProFluentCRM\Triggers\LessonCompletedTrigger;
use FluentCampaign\App\Services\MetaFormBuilder;
use FluentCrm\App\Models\Tag;
use FluentCrm\App\Services\Html\TableBuilder;

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

class Integrations {


	public static function init() {

		$self = new self();
		add_action('fluentcrm_loaded', function () {
			// registering triggers
			new CourseEnrollTrigger();
			new CourseCompletedTrigger();
			new LessonCompletedTrigger();

			// registering actions
			new AddToCourseAction();
			new RemoveFromCourseAction();

			// automation conditions
			( new AutomationConditions() )->init();

			if ( Helper::is_plugin_active( 'fluentcampaign-pro/fluentcampaign-pro.php' ) ) {
				// integration with FluentCRM
				( new DeepIntegration() )->init();
				// smart codes for email
				( new AcademyShortCodes() )->init();
				// academy-lms importer
				new AcademyImporter();
			}

		});

		// add icon for FluentCRM
		add_filter('fluent_crm/funnel_icons', function ( $icons ) {
			$icons['academylms'] = 'dashicons dashicons-welcome-learn-more';

			return $icons;
		});

		add_filter( 'fluentcrm_profile_sections', array( $self, 'push_courses_on_profile' ) );
		add_filter( 'fluencrm_profile_section_academy_profile_courses', array( $self, 'push_courses_content' ), 10, 2 );
		add_filter( 'fluent_crm/subscriber_info_widgets', array( $self, 'push_subscriber_info_widget' ), 10, 2 );

		if ( ! apply_filters( 'fluentcrm_disable_integration_metaboxes', false, 'academylms' ) && Helper::is_plugin_active( 'fluentcampaign-pro/fluentcampaign-pro.php' ) ) {
			add_action( 'add_meta_boxes', array( $self, 'add_course_metabox' ), 10 );
			add_action( 'save_post_academy_courses', array( $self, 'save_course_metabox' ) );
			add_action( 'academy/admin/course_complete_after', array( $self, 'maybe_course_completed_tags' ), 50, 2 );
			add_action( 'academy/course/after_enroll', array( $self, 'maybe_course_enrolled_tags' ), 50, 2 );
		}

	}


	public function push_courses_on_profile( $sections ) {
		$sections['academy_profile_courses'] = [
			'name' => 'fluentcrm_profile_extended',
			'title' => __( 'Courses', 'academy-pro' ),
			'handler' => 'route',
			'query' => [
				'handler' => 'academy_profile_courses'
			]
		];

		return $sections;
	}

	public function push_courses_content( $content, $subscriber ) {
		$content['heading'] = __( 'AcademyLMS Courses', 'academy-pro' );

		$userId = $subscriber->user_id;

		if ( ! $userId ) {
			$content['content_html'] = '<p>' . __( 'No enrolled courses found for this contact', 'academy-pro' ) . '</p>';

			return $content;
		}

		$courseIds = \AcademyProFluentCRM\Helper::get_user_courses( $userId );

		if ( empty( $courseIds ) ) {
			$content['content_html'] = '<p>' . __( 'No enrolled courses found for this contact', 'academy-pro' ) . '</p>';

			return $content;
		}

		$enrolledCourses = get_posts([
			'post_type' => 'academy_courses',
			'posts_per_page' => 100,
			'post__in' => $courseIds,
		]);

		$tableBuilder = new TableBuilder();
		foreach ( $enrolledCourses as $course ) {
			$enrolled = fluentCrmDb()->table( 'posts' )
				->where( 'post_parent', $course->ID )
				->where( 'post_author', $userId )
				->where( 'post_type', 'academy_enrolled' )
				->first();

			$completed_count = Helper::get_percentage_of_completed_topics_by_student_and_course_id($userId,
			$course->ID);

			$tableBuilder->addRow([
				'id' => $course->ID,
				'title' => $course->post_title,
				'progress' => $completed_count . '%',
				'started_at' => date_i18n( get_option( 'date_format' ), strtotime( $enrolled->post_date ) ),
			]);
		}

		$tableBuilder->setHeader([
			'id' => __( 'ID', 'academy-pro' ),
			'title' => __( 'Course Name', 'academy-pro' ),
			'started_at' => __( 'Started At', 'academy-pro' ),
			'progress' => __( 'Progress', 'academy-pro' )
		]);

		$content['content_html'] = $tableBuilder->getHtml();

		return $content;
	}

	public function add_course_metabox( $post_id ) {
		add_meta_box('fcrm_course_tags', __( 'FluentCRM - Course Tags', 'academy-pro' ), function ( $post ) {

			$tagSettings = wp_parse_args(get_post_meta( $post->ID, '_fluentcrm_settings', true ), [
				'enrolled_tags' => [],
				'completed_tags' => []
			]);

			$formattedTags = [];
			foreach ( Tag::get() as $tag ) {
				$formattedTags[] = [
					'key' => $tag->id,
					'title' => $tag->title
				];
			}

			$formBuilder = new MetaFormBuilder();
			$formBuilder->addField([
				'class' => 'academy_select2',
				'data_attributes' => array(
					'data-placeholder' => __( 'Select Tags', 'academy-pro' ),
				),
				'desc' => __( 'Selected tags will be applied to the contact on course enrollment.', 'academy-pro' ),
				'name' => '_fluentcrm_settings[enrolled_tags][]',
				'label' => __( 'Apply Tags on course enrollment', 'academy-pro' ),
				'multi' => true,
				'type' => 'select',
				'options' => $formattedTags,
				'value' => $tagSettings['enrolled_tags'],
			]);

			$formBuilder->addField([
				'class' => 'academy_select2',
				'data_attributes' => array(
					'data-placeholder' => __( 'Select Tags', 'academy-pro' ),
				),
				'desc' => __( 'Selected tags will be applied to the contact on course completion.', 'academy-pro' ),
				'name' => '_fluentcrm_settings[completed_tags][]',
				'label' => __( 'Apply Tags on course completion', 'academy-pro' ),
				'multi' => true,
				'type' => 'select',
				'options' => $formattedTags,
				'value' => $tagSettings['completed_tags'],
			]);

			$formBuilder->renderFields();

		}, 'academy_courses');
	}

	public function save_course_metabox( $postId ) {
		// nonce verificaion
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		if ( ! isset( $_POST['fcrm_course_tags_nonce'] ) || ! wp_verify_nonce( $_POST['fcrm_course_tags_nonce'], 'fcrm_course_tags' ) ) {
			return;
		}
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$fluentcrm_settings = sanitize_text_field( $_POST['_fluentcrm_settings'] );

		$settings = [
			'enrolled_tags' => [],
			'completed_tags' => []
		];

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		if ( isset( $_POST['_fluentcrm_settings'] ) ) {
			$settings = $fluentcrm_settings;
		}

		update_post_meta( $postId, '_fluentcrm_settings', $settings );
	}

	public function maybe_course_enrolled_tags( $courseId, $userId ) {
		$settings = get_post_meta( $courseId, '_fluentcrm_settings', true );
		if ( ! $settings || empty( $settings['enrolled_tags'] ) || ! is_array( $settings['enrolled_tags'] ) ) {
			return false;
		}
		\AcademyProFluentCRM\Helper::create_contact_from_academy( $userId, $settings['enrolled_tags'] );

		return true;
	}

	public function maybe_course_completed_tags( $courseId, $userId ) {
		$settings = get_post_meta( $courseId, '_fluentcrm_settings', true );
		if ( ! $settings || empty( $settings['completed_tags'] ) || ! is_array( $settings['completed_tags'] ) ) {
			return false;
		}

		\AcademyProFluentCRM\Helper::create_contact_from_academy( $userId, $settings['completed_tags'] );

		return true;
	}

	public function push_subscriber_info_widget( $widgets, $subscriber ) {
		if ( ! $subscriber->user_id ) {
			return $widgets;
		}

		$userId = $subscriber->user_id;

		$courseIds = \AcademyProFluentCRM\Helper::get_user_courses( $userId );

		if ( empty( $courseIds ) ) {
			return $widgets;
		}

		$enrolledCourses = get_posts([
			'post_type' => 'academy_courses',
			'posts_per_page' => 100,
			'post__in' => $courseIds,
		]);

		if ( ! $enrolledCourses ) {
			return $widgets;
		}

		$html = '<ul class="fc_full_listed">';
		foreach ( $enrolledCourses as $course ) {
			$html .= '<li><a target="_blank" rel="noopener" href="' . get_permalink( $course->ID ) . '">' . $course->post_title . '</a></li>';
		}
		$html .= '</ul>';

		$widgets[] = [
			'title' => 'Course Enrollments',
			'content' => $html
		];

		return $widgets;
	}

}
