<?php

namespace AcademyProFluentCRM;

use FluentCampaign\App\Services\Commerce\ContactRelationItemsModel;
use FluentCrm\App\Models\FunnelSubscriber;

class AcademyShortCodes {

	public function init() {
		add_filter( 'fluent_crm/smartcode_group_callback_al', array( $this, 'parse_academy_codes' ), 10, 4 );
		add_filter( 'fluent_crm/extended_smart_codes', array( $this, 'push_general_codes' ) );
		add_filter( 'fluent_crm_funnel_context_smart_codes', array( $this, 'push_context_codes' ), 14, 2 );
	}

	public function parse_academy_codes( $code, $valueKey, $defaultValue, $subscriber ) {
		$userId = $subscriber->getWpUserId();

		if ( ! $userId ) {
			return $defaultValue;
		}

		/*
		 * General Student Items
		 */
		switch ( $valueKey ) {
			case 'courses':
				$courses = Helper::get_user_courses( $userId );
				$coursesNames = array();
				if ( ! empty( $courses ) && is_array( $courses ) ) {
					foreach ( $courses as $course_id ) {
						$coursesNames[] = get_the_title( $course_id );
					}
				}

				return implode( ', ', $coursesNames );
			case 'courses_link':
				$courses = Helper::get_user_courses( $userId );
				$coursesNames = array();
				if ( ! empty( $courses ) && is_array( $courses ) ) {
					foreach ( $courses as $course_id ) {
						$coursesNames[] = [
							'title' => get_the_title( $course_id ),
							'permalink' => get_the_permalink( $course_id )
						];
					}
				}

				if ( ! $coursesNames ) {
					return $defaultValue;
				}

				$html = '<ul class="academy_courses">';
				foreach ( $coursesNames as $coursesName ) {
					$html .= '<li><a href="' . $coursesName['permalink'] . '">' . $coursesName['title'] . '</a>';
				}
				$html .= '</ul>';

				return $html;
		}//end switch

		/*
		 * Contextual Course / Topic Related SmartCodes
		 */
		$triggerSource = false;
		$triggerId = false;

		if ( ! empty( $subscriber->funnel_subscriber_id ) ) {
			$funnelSub = FunnelSubscriber::where( 'id', $subscriber->funnel_subscriber_id )->first();
			if ( $funnelSub ) {
				$triggerSource = Helper::get_trigger_source( $funnelSub->source_trigger_name );
				$triggerId = $funnelSub->source_ref_id;
			}
		}

		$courseItems = [ 'course_name', 'course_href', 'course_name_linked' ];
		if ( 'course' === $triggerSource && ! in_array( $valueKey, $courseItems, true ) ) {
			$triggerId = false;
		}

		if ( ! $triggerId ) {
			return $defaultValue;
		}

		if ( ! $triggerId ) {
			if ( in_array( $valueKey, $courseItems, true ) ) {
				$itemType = 'course';
			} else {
				return $defaultValue;
			}

			$item = ContactRelationItemsModel::provider( 'academylms' )
				->where( 'subscriber_id', $subscriber->id )
				->where( 'item_type', $itemType )
				->orderBy( 'created_at', 'DESC' )
				->first();

			if ( $item ) {
				$triggerId = $item->item_id;
			}
		}

		if ( ! $triggerId ) {
			return $defaultValue;
		}

		switch ( $valueKey ) {
			case 'course_name':
				return get_the_title( $triggerId );
			case 'course_href':
				return get_the_permalink( $triggerId );
			case 'course_name_linked':
				$title = get_the_title( $triggerId );
				if ( $title ) {
					return '<a href="' . get_the_permalink( $triggerId ) . '">' . $title . '</a>';
				}

				return $defaultValue;
		}
	}

	public function push_general_codes( $codes ) {
		$codes['academylms'] = [
			'key' => 'academylms',
			'title' => 'AcademyLMS',
			'shortcodes' => $this->get_smart_codes()
		];

		return $codes;
	}

	private function get_smart_codes( $context = '' ): array {
		$generalCodes = [
			'{{al.courses}}' => 'User Enrolled Course Names (Comma Separated)',
			'{{al.courses_link}}' => 'User Enrolled Course with links (list)',
			'{{al.course_name}}' => 'Current Course Title',
			'{{al.course_name_linked}}' => 'Current Course Title with Hyperlink',
			'##al.course_href##' => 'HTTP Link of the current course'
		];

		if ( ! $context ) {
			return $generalCodes;
		}

		$courseContext = [
			'{{al.course_name}}' => 'Current Course Title',
			'{{al.course_name_linked}}' => 'Current Course Title with Hyperlink',
			'##al.course_href##' => 'HTTP Link of the current course'
		];

		if ( 'all' === $context ) {
			return array_merge( $generalCodes, $courseContext );
		} elseif ( 'course' === $context ) {
			return $courseContext;
		}

		return [];
	}

	public function push_context_codes( $codes, $context ) {
		$triggerSource = Helper::get_trigger_source( $context );
		if ( ! $triggerSource ) {
			return $codes;
		}

		if ( 'course' === $triggerSource ) {
			$codes[] = [
				'key' => 'al_course',
				'title' => 'Enrolled Course',
				'shortcodes' => $this->get_smart_codes( $triggerSource )
			];

			return $codes;
		}

		return $codes;
	}
}
