<?php

defined( 'ABSPATH' ) || exit;

/**
 * Course Preview helper functions.
 *
 * @since 2.6.7
 * @version 2.6.7
 *
 * @package Masteriyo\Pro\Addons\CoursePreview\Helper
 */

use Masteriyo\Enums\PostStatus;
use Masteriyo\Enums\VideoSource;
use Masteriyo\PostType\PostType;

/**
 * Retrieve the video URLs for previewable lessons in a course.
 *
 * @since 2.6.7
 *
 * @param int $course_id The ID of the course to retrieve lessons from.
 *
 * @return array An array of video URLs for previewable lessons.
 */
function masteriyo_get_previewable_lessons_video_data( $course_id ) {
	$course_contents = masteriyo_get_course_contents( $course_id );

	if ( empty( $course_contents ) ) {
		return array();
	}

	$lessons = array_filter(
		$course_contents,
		function( $course_content ) {
			return PostType::LESSON === $course_content->get_post_type();
		}
	);

	// Filter empty video source embed url or preview is not enable.
	$lessons = array_filter(
		$lessons,
		function( $lesson ) {
			return ( trim( $lesson->get_video_source_embed_url() ) || VideoSource::EMBED === $lesson->get_video_source() ) && $lesson->get_enable_video_preview();
		}
	);

	$videos_data = array_map(
		function( $lesson ) {
			$embed_url = '';
			if ( VideoSource::EMBED === $lesson->get_video_source() ) {

				preg_match( '/<iframe.*?src=["\'](.*?)["\'].*?>/i', $lesson->get_video_source_url(), $matches );
				if ( isset( $matches[1] ) ) {
					$src       = $matches[1] ?? '';
					$embed_url = $src;

				}
			}
			return array(
				'id'            => $lesson->get_id(),
				'lesson_name'   => $lesson->get_name(),
				'video_url'     => $embed_url ? $embed_url : $lesson->get_video_source_embed_url(),
				'thumbnail_url' => $lesson->get_featured_image_url(),
				'video_source'  => $lesson->get_video_source(),
				'video_length'  => masteriyo_get_formatted_lesson_video_length( $lesson ),
				'is_iframe'     => ( VideoSource::SELF_HOSTED === $lesson->get_video_source() ) ? 'false' : 'true',
			);
		},
		$lessons
	);

	return $videos_data;
}

/**
 * Check if video preview is enabled for a lesson.
 *
 * @since 2.6.7
 *
 * @param int $lesson The lesson ID to check for video preview.
 *
 * @return bool True if video preview is enabled for the lesson, false otherwise.
 */
function masteriyo_course_preview_is_lesson_video_preview_enabled( $lesson ) {
	$lesson = masteriyo_get_lesson( $lesson );

	if ( is_null( $lesson ) ) {
		return false;
	}

	return masteriyo_string_to_bool( $lesson->get_enable_video_preview() );
}

/**
 * Check if lesson preview is enabled for a lesson.
 *
 * @since 2.7.1
 *
 * @param int $lesson The lesson ID to check for lesson preview.
 *
 * @return bool True if lesson preview is enabled for the lesson, false otherwise.
 */
function masteriyo_course_preview_is_lesson_preview_enabled( $lesson ) {
	$lesson = masteriyo_get_lesson( $lesson );

	if ( is_null( $lesson ) || is_wp_error( $lesson ) ) {
		return false;
	}

	return masteriyo_string_to_bool( $lesson->get_enable_preview() );
}

/**
 * Get the formatted length of the lesson video.
 *
 * If hour is 0, return the formatted length as mm:ss.
 * If hour and minute are both zero, return the formatted length as ss.
 * If hour, minute, and second are all zero, return 'N/A'.
 *
 * @since 2.6.7
 *
 * @param \Masteriyo\Models\Lesson|int|\WP_Post $lesson .
 *
 * @return string The formatted length of the lesson video.
 */
function masteriyo_get_formatted_lesson_video_length( $lesson ) {
	$lesson = masteriyo_get_lesson( $lesson );
	$result = _x( 'N/A', 'Lesson video length not available', 'learning-management-system' );

	if ( $lesson && $lesson->get_video_playback_time() ) {
		list($hours, $minutes, $seconds) = masteriyo_convert_seconds_to_hours_minutes_seconds( $lesson->get_video_playback_time() );
		$result                          = sprintf( '%02d:%02d:%02d', $hours, $minutes, $seconds );
	}

	/**
	 * Filters formatted video length.
	 *
	 * @since 2.6.7
	 *
	 * @param string $result Formatted video length.
	 *
	 * @param \Masteriyo\Models\Lesson|null $lesson
	 */
	return apply_filters( 'masteriyo_lesson_formatted_video_length', $result, $lesson );
}

/**
 * Convert seconds into hours, minutes, and seconds.
 *
 * @since 2.6.7
 *
 * @param int $total_seconds The total number of seconds to convert.
 *
 * @return array An array containing hours, minutes, and seconds.
 */
function masteriyo_convert_seconds_to_hours_minutes_seconds( $total_seconds ) {
	$hours   = floor( $total_seconds / HOUR_IN_SECONDS );
	$minutes = floor( ( $total_seconds % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );
	$seconds = $total_seconds % MINUTE_IN_SECONDS;
	return array( $hours, $minutes, $seconds );
}

/**
 * Determines if a course contains any lessons that are previewable.
 *
 * This function checks if a given course has any lessons that have been marked as previewable.
 *
 * @since 2.7.1
 *
 * @param int $course_id The unique identifier of the course to inspect.
 *
 * @return bool Returns true if the course contains at least one previewable lesson, otherwise false.
 */
function masteriyo_has_previewable_lessons_for_course( $course_id ) {

	if ( empty( $course_id ) ) {
			return false;
	}

	$args = array(
		'post_type'      => PostType::LESSON,
		'posts_per_page' => -1,
		'fields'         => 'ids',
		'meta_query'     => array(
			'relation' => 'AND',
			array(
				'key'     => '_course_id',
				'value'   => $course_id,
				'compare' => '=',
			),
			array(
				'key'     => '_enable_preview',
				'value'   => true,
				'compare' => '=',
			),
		),
	);

	$lesson_query = new \WP_Query( $args );

	// Return true if there's at least one lesson that's previewable for the course.
	return $lesson_query->found_posts > 0;
}

/**
 * Retrieves the IDs of previewable lessons for a given course.
 *
 * This function retrieves an array of lesson IDs that are marked as previewable for the specified course.
 *
 * @since 2.7.1
 *
 * @param int $course_id The unique identifier of the course to inspect.
 *
 * @return array|false An array of lesson IDs if previewable lessons are found, otherwise false.
 */
function masteriyo_get_previewable_lesson_ids_for_course( $course_id ) {
	if ( empty( $course_id ) ) {
		return false;
	}

	$section_ids = get_posts(
		array(
			'post_type'      => PostType::SECTION,
			'post_status'    => PostStatus::PUBLISH,
			'post_parent'    => $course_id,
			'posts_per_page' => -1,
			'fields'         => 'ids',
		)
	);

	if ( empty( $section_ids ) ) {
		return false;
	}

	$lesson_ids = array();
	foreach ( $section_ids as $section_id ) {
		$posts = get_posts(
			array(
				'post_type'      => PostType::LESSON,
				'post_status'    => PostStatus::PUBLISH,
				'post_parent'    => $section_id,
				'posts_per_page' => -1,
				'orderby'        => 'menu_order',
				'order'          => 'asc',
				'fields'         => 'ids',
				'meta_query'     => array(
					'relation' => 'AND',
					array(
						'key'     => '_course_id',
						'value'   => $course_id,
						'compare' => '=',
					),
					array(
						'key'     => '_enable_preview',
						'value'   => true,
						'compare' => '=',
					),
				),
			)
		);
		array_push( $lesson_ids, ...$posts );
	}

	return $lesson_ids;
}
