<?php

namespace ThimPress\ThimBlocks\Gutenberg\Blocks\Courses;

use ThimPress\ThimBlocks\Gutenberg\Blocks\AbstractBlockType;
use LearnPress\Helpers\Template;
use LearnPress\Models\Courses;
use LearnPress\TemplateHooks\Instructor\SingleInstructorTemplate;
use LearnPress\TemplateHooks\TemplateAJAX;
use LP_Course_Filter;
use LP_Debug;
use LP_Page_Controller;
use stdClass;
use Throwable;
use WP_Block;

/**
 * Class CoursesBlockType
 *
 * @since 4.2.8.3
 * @version 1.0.2
 */
class CoursesBlockType extends AbstractBlockType {

	public $block_name = 'courses';

	public function __construct() {
		add_filter( 'lp/rest/ajax/allow_callback', [ $this, 'allow_callback' ] );
		parent::__construct();
	}

	/**
	 * Get supports of block
	 *
	 * @return array
	 */
	public function get_supports() {
		return [
			'align' => [ 'wide', 'full' ],
		];
	}

	/**
	 * Allow callback for block
	 *
	 * @param array $callbacks.
	 *
	 * @return array
	 */
	public function allow_callback( array $callbacks ): array {
		$callbacks[] = get_class( $this ) . ':render_courses';
		return $callbacks;
	}

	/**
	 * Render content of block tag
	 *
	 * @param array $attributes | Attributes of block tag.
	 *
	 * @return false|string
	 * @since 4.2.8.3
	 * @version 1.0.2
	 */
	public function render_content_block_template( array $attributes, $content, $block ): string {
		wp_enqueue_script( 'lp-courses-v2' );

		// Note: Wishlist assets might be enqueued globally by the addon
		// Test without explicit enqueue to see if it still workss
		if ( class_exists( 'LP_Addon_Wishlist' ) ) {
			wp_enqueue_style( 'lp-course-wishlist' );
			wp_enqueue_script( 'lp-course-wishlist-script' );
		}

		// Enqueue slider assets if slider is enabled
		$slider = $attributes['slider'] ?? [];
		if ( ! empty( $slider['enable'] ) ) {
			// Only enqueue courses slider script (Swiper will be bundled in JS)
			$handle = 'thim-blocks-view-' . $this->block_name;
			wp_enqueue_script( $handle );
		}

		$html = '';

		try {
			$args                 = lp_archive_skeleton_get_args();
			$args['id_url']       = 'gutenberg-list-courses';
			$args['attributes']   = $attributes;
			$args['parsed_block'] = $block->parsed_block;
			$courseQuery          = $attributes['courseQuery'] ?? [];
			$gridGap              = $attributes['gridGap'] ?? 20;
			$callback             = [
				'class'  => get_class( $this ),
				'method' => 'render_courses',
			];
			$html_wrapper         = [
				'<div class="lp-list-courses-default">' => '</div>',
			];

			// For case instructor page, show courses of instructor
			if ( LP_Page_Controller::is_page_instructor() ) {
				$instructor = SingleInstructorTemplate::instance()->detect_instructor_by_page();
				if ( $instructor && $instructor->is_instructor() ) {
					$args['c_author'] = $instructor->get_id();
				}
			}

			$html = TemplateAJAX::load_content_via_ajax( $args, $callback );
			$html = Template::instance()->nest_elements( $html_wrapper, $html );

			// Add slider wrapper if slider is enabled
			if ( ! empty( $slider['enable'] ) ) {
				$slider_attrs = sprintf(
					'data-slider="true" data-slides-to-show="%d" data-slides-to-scroll="%d" data-space-between="%d" data-autoplay="%s" data-autoplay-speed="%d" data-dots="%s" data-dot-style="%s" data-arrows="%s" data-nav-style="%s" data-infinite="%s" data-responsive-tablet="%d" data-responsive-mobile="%d"',
					$slider['slidesToShow'] ?? 3,
					$slider['slidesToScroll'] ?? 1,
					$slider['spaceBetween'] ?? 30,
					( $slider['autoplay'] ?? false ) ? 'true' : 'false',
					$slider['autoplaySpeed'] ?? 3000,
					( $slider['dots'] ?? true ) ? 'true' : 'false',
					$slider['dotStyle'] ?? 'default',
					( $slider['arrows'] ?? true ) ? 'true' : 'false',
					$slider['navStyle'] ?? 'default',
					( $slider['infinite'] ?? true ) ? 'true' : 'false',
					$slider['responsive']['tablet']['slidesToShow'] ?? 2,
					$slider['responsive']['mobile']['slidesToShow'] ?? 1
				);

				$dotOffset = isset( $slider['dotOffset'] ) ? $slider['dotOffset'] : -50;
				$navOffset = isset( $slider['navOffset'] ) ? $slider['navOffset'] : 30;

				$custom_styles = '';
				if ( ! empty( $slider['navSize'] ) ) {
					$custom_styles .= sprintf( ' --nav-size: %dpx;', $slider['navSize'] );
				}
				if ( ! empty( $slider['navColor'] ) ) {
					$custom_styles .= sprintf( ' --nav-color: %s;', esc_attr( $slider['navColor'] ) );
				}
				if ( ! empty( $slider['navBackground'] ) ) {
					$custom_styles .= sprintf( ' --nav-bg: %s;', esc_attr( $slider['navBackground'] ) );
				}
				if ( ! empty( $slider['navHoverColor'] ) ) {
					$custom_styles .= sprintf( ' --nav-hover-color: %s;', esc_attr( $slider['navHoverColor'] ) );
				}
				if ( ! empty( $slider['navHoverBackground'] ) ) {
					$custom_styles .= sprintf( ' --nav-hover-bg: %s;', esc_attr( $slider['navHoverBackground'] ) );
				}
				if ( ! empty( $slider['dotColor'] ) ) {
					$custom_styles .= sprintf( ' --dot-color: %s;', esc_attr( $slider['dotColor'] ) );
				}
				if ( ! empty( $slider['dotHoverColor'] ) ) {
					$custom_styles .= sprintf( ' --dot-active-color: %s;', esc_attr( $slider['dotHoverColor'] ) );
				} elseif ( ! empty( $slider['dotActiveColor'] ) ) {
					$custom_styles .= sprintf( ' --dot-active-color: %s;', esc_attr( $slider['dotActiveColor'] ) );
				}

				$html = sprintf( '<div class="thim-courses-slider" %s style="--gap: %dpx; --swiper-pagination-bottom: %dpx; --swiper-navigation-sides-offset: %dpx;%s">%s</div>', $slider_attrs, $gridGap, $dotOffset, $navOffset, $custom_styles, $html );
			} else {
				// Add grid gap style for normal grid layout
				$html = sprintf( '<div style="--gap: %dpx;">%s</div>', $gridGap, $html );
			}

			return $this->get_output( $html );
		} catch ( Throwable $e ) {
			LP_Debug::error_log( $e );
		}

		return $html;
	}

	/**
	 * Render template list courses with settings param.
	 *
	 * @param array $settings
	 *
	 * @return stdClass { content: string_html }
	 * @since 4.2.8.4
	 * @version 1.0.1
	 */
	public static function render_courses( array $settings = [] ): stdClass {
		$content          = new stdClass();
		$content->content = '';

		$parsed_block = $settings['parsed_block'] ?? '';
		$attributes   = $settings['attributes'] ?? [];
		$courseQuery  = $attributes['courseQuery'] ?? [];
		$total_rows   = 0;

		// If we have category filter, use custom WP_Query
		if ( ! empty( $courseQuery['term_slug'] ) ) {
			$category_slugs = explode( ',', $courseQuery['term_slug'] );
			$category_slugs = array_filter( array_map( 'trim', $category_slugs ) );

			if ( ! empty( $category_slugs ) ) {
				$query_args = [
					'post_type'      => 'lp_course',
					'post_status'    => 'publish',
					'posts_per_page' => $courseQuery['limit'] ?? 10,
					'tax_query'      => [
						[
							'taxonomy' => 'course_category',
							'field'    => 'slug',
							'terms'    => $category_slugs,
							'operator' => 'IN',
						],
					],
				];

				// Handle order_by
				switch ( $courseQuery['order_by'] ?? 'post_date' ) {
					case 'post_title':
						$query_args['orderby'] = 'title';
						$query_args['order']   = 'ASC';
						break;
					case 'post_title_desc':
						$query_args['orderby'] = 'title';
						$query_args['order']   = 'DESC';
						break;
					case 'post_date':
					default:
						$query_args['orderby'] = 'date';
						$query_args['order']   = 'DESC';
						break;
				}

				$custom_query = new \WP_Query( $query_args );
				$courses      = $custom_query->posts;
				$total_rows   = $custom_query->found_posts;
			} else {
				$courses = [];
			}
		} else {
			// No category filter, use LearnPress default
			$filter               = new LP_Course_Filter();
			$settings['order_by'] = $courseQuery['order_by'] ?? 'post_date';
			$settings['limit']    = $courseQuery['limit'] ?? 10;

			Courses::handle_params_for_query_courses( $filter, $settings );
			$filter  = apply_filters( 'learn-press/block/list_courses/handle_filter', $filter, $settings );
			$courses = Courses::get_courses( $filter, $total_rows );
		}

		$paged        = $settings['paged'] ?? 1;
		$results_data = [];

		if ( ! empty( $courses ) ) {
			$results_data = [
				'paged'            => $paged,
				'courses_per_page' => $courseQuery['limit'] ?? 10,
				'total_rows'       => $total_rows,
			];
		}

		$filter_block_context = static function ( $context ) use ( $courses, $results_data, $settings ) {
			$context['is_list_course'] = true;
			$context['courses']        = $courses ?? [];
			$context['settings']       = $settings;
			$context['results_data']   = $results_data;
			return $context;
		};

		// Add filter with priority 1 so other filters have access to these values
		add_filter( 'render_block_context', $filter_block_context, 1 );
		$block_render  = new WP_Block( $parsed_block );
		$block_content = $block_render->render( [ 'dynamic' => false ] );
		remove_filter( 'render_block_context', $filter_block_context, 1 );

		$content->content = $block_content;
		$content->paged   = $settings['paged'] ?? 1;

		return $content;
	}

}
