<?php

namespace MEC_Advanced_Speaker\Core\SpeakerWidget;

use \MEC_Advanced_Speaker\Core\Lib\MEC_Advanced_Speaker_Lib_Skin;
use \MEC_Advanced_Speaker\Core\Lib\MEC_Advanced_Speaker_Lib_Factory;

/**
 * Webnus MEC Speaker Backend Widget class.
 * @author Webnus <info@webnus.biz>
 */
class MEC_Advanced_Speaker_SpeakerWidget_Frontend {
	public static $factory;

	/**
	 * Instance of this class.
	 *
	 * @since   1.0.0
	 * @access  public
	 * @var     MEC_Featured
	 */
	public static $instance;

	/**
	 * The directory of the file.
	 *
	 * @access  public
	 * @var     string
	 */
	public static $dir;

	/**
	 * Provides access to a single instance of a module using the singleton pattern.
	 *
	 * @since   1.0.0
	 * @return  object
	 */
	public static function instance() {
		if (self::$instance === null) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Constructor method
	 * @author Webnus <info@webnus.biz>
	 */
	public function __construct() {

		self::$dir = MEC_ADVANCED_SPEAKER_DIR . 'core' . DS . 'speakerWidget' . DS;

		add_action('init', function () {
			self::init($this);
		}, 10, 1);
	}

	public static function init($class) {
		// Import MEC Factory
		self::$factory = \MEC::getInstance('app.libraries.factory');

		$edit = isset($_GET['action'])? trim($_GET['action']) : null;
		$post = isset($_GET['post']) && is_string($_GET['post']) ? trim($_GET['post']) : null;
		$rest_route = isset($_GET['rest_route']) ? $_GET['rest_route'] : null;

		/**
		 * Current Wordpress gutenberg Bug on shortcode
		 * @link(stackoverflow, https://wordpress.stackexchange.com/questions/360279)
		 * @link(wordpress, https://wordpress.org/support/topic/fatal-error-with-wordpress-5-0-2-guteberg-editor/)
		 *
		 * @todo after filxed bug on next version remove the checked!
		 */
		 if( (is_admin() && $edit=='edit' && $post!=null) || $rest_route != null){
			// cannot load
		}else{

			self::$factory->shortcode('mec-speaker', array($class, 'single_speaker_content'));
			self::$factory->shortcode('speaker-list', array(__CLASS__, 'speaker_list_content'));
			self::$factory->shortcode('speaker-featured', array(__CLASS__, 'speaker_featured_content'));
		}

		self::$factory->action('wp_ajax_mec_featured_speaker_load_more', array($class, 'load_more'));
		self::$factory->action('wp_ajax_nopriv_mec_featured_speaker_load_more', array($class, 'load_more'));

	}

	public static function single_speaker_content($atts = null, $content = '', $load_assets = true) {

		$atts = MEC_Advanced_Speaker_Lib_Factory::extract_attrs($atts, true, 'speaker');

		$term = get_term($atts['id'], 'mec_speaker', ARRAY_A);
		$meta = MEC_Advanced_Speaker_Lib_Factory::get_meta_key_val($atts['id'],$atts['exclude_details']);

		$featured = get_metadata('term', $atts['id'], 'featured', true) == 1;

		if (!$term || count($term) == 0) {
			echo '<p>'.__( 'Speaker Not Found!', 'mec-advanced-speaker' ).'</p>';
			return null;
		}

		if ($atts['events_style'] == 'grid') {
			$path = \MEC::import('app.skins.tile', true, true);
			include_once $path;
			$skin_class_name = 'MEC_skin_tile';
			$atts['skin'] = 'tile';
		} else {
			$path = \MEC::import('app.skins.list', true, true);
			include_once $path;
			$skin_class_name = 'MEC_skin_list';
			$atts['skin'] = 'list';
			$atts['sk-options']['list']['style'] = 'standard';
		}

		$atts['sk-options'][$atts['skin']]['next_previous_button'] = false;

		// Create Skin Object Class
		$SKO = new $skin_class_name();
		$SKO->skin = $atts['skin'];

		$atts['speaker'] = $atts['id'];
		
		// Set from_advanced_speaker_addon flag (always set it, we'll handle ongoing/past events separately)
		$atts['from_advanced_speaker_addon'] = true;
		
		// Set show_only_ongoing_events for MEC skin (it expects this name, not only_ongoing_events)
		if (isset($atts['only_ongoing_events']) && $atts['only_ongoing_events'] == true) {
			$atts['show_only_ongoing_events'] = '1';
		}
		
		// Set show_past_events for show_only_past_events
		if (isset($atts['show_only_past_events']) && $atts['show_only_past_events'] == true) {
			$atts['show_only_past_events'] = '1';
			$atts['show_past_events'] = '1';
		}

		// Initialize the skin
		$SKO->initialize($atts);
		
		// Set from_advanced_speaker_addon flag on SKO object (suppress deprecated warning)
		if (isset($atts['from_advanced_speaker_addon']) && $atts['from_advanced_speaker_addon']) {
			// Suppress deprecated warning for dynamic property
			@$SKO->from_advanced_speaker_addon = true;
			
			// Set maximum_date to far future to show all events (unless only_ongoing_events is active or maximum_date is set in atts)
			// This ensures all events are found, not just events in current month
			if (!isset($atts['only_ongoing_events']) || $atts['only_ongoing_events'] != true) {
				// Only set default maximum_date if not provided in atts
				if (!isset($atts['maximum_date']) || empty($atts['maximum_date'])) {
					if (!isset($SKO->maximum_date) || empty($SKO->maximum_date)) {
						$SKO->maximum_date = date('Y-m-d', strtotime('+10 years'));
					}
					
					// Also set maximum_date_range to ensure all events are included
					if (!isset($SKO->maximum_date_range) || empty($SKO->maximum_date_range)) {
						$SKO->maximum_date_range = date('Y-m-d', strtotime('+10 years'));
					}
				}
			}
		}

		// MEC skin reads load_more_button from skin_options (which is set in extract_attrs)
		// So we don't need to set it manually here - it's already in $atts['sk-options']

		// Suppress deprecated warning for dynamic property
		@$SKO->load_method = 'list';

		if (isset($atts['only_ongoing_events']) && $atts['only_ongoing_events'] == true) {
			$SKO->show_ongoing_events = true;
		}

		if ($atts['events_style'] == 'list') {
			$SKO->style = 'standard';
		}

		$meta['section'] = 'speaker';

		// Set start_date and end_date from shortcode attributes or defaults
		// This must be done after initialize() but before fetch()
		// Only set dates if not showing only ongoing events (ongoing events need start_date = today)
		if (isset($SKO->from_advanced_speaker_addon) && $SKO->from_advanced_speaker_addon) {
			// If only_ongoing_events is active, don't override start_date (let MEC handle it)
			if (!isset($atts['only_ongoing_events']) || $atts['only_ongoing_events'] != true) {
				// If show_only_past_events is active, don't override dates (let MEC handle it)
				if (!isset($atts['show_only_past_events']) || $atts['show_only_past_events'] != true) {
					// If start_date is provided in shortcode, use it
					if (isset($atts['start_date']) && !empty($atts['start_date'])) {
						$SKO->start_date = date('Y-m-d', strtotime($atts['start_date']));
					} else {
						// Otherwise, set start_date to past to show all events
						$SKO->start_date = date('Y-m-d', strtotime('-10 years'));
					}
					
					// Reset end_date to start_date (will be extended in fetch loop)
					$SKO->end_date = $SKO->start_date;
					
					// If maximum_date is provided in shortcode, use it (this overrides any default)
					if (isset($atts['maximum_date']) && !empty($atts['maximum_date'])) {
						$SKO->maximum_date = date('Y-m-d', strtotime($atts['maximum_date']));
						// Also set maximum_date_range to the same value
						$SKO->maximum_date_range = $SKO->maximum_date;
					} elseif (!isset($SKO->maximum_date) || empty($SKO->maximum_date)) {
						// Otherwise, set maximum_date to far future (only if not already set)
						$SKO->maximum_date = date('Y-m-d', strtotime('+10 years'));
						if (!isset($SKO->maximum_date_range) || empty($SKO->maximum_date_range)) {
							$SKO->maximum_date_range = date('Y-m-d', strtotime('+10 years'));
						}
					}
				}
			}
		}
		
		// IMPORTANT: Always apply maximum_date from atts if set, even after initialize()
		// This ensures maximum_date is not overridden by initialize() or other MEC logic
		// This MUST be done right before fetch() to prevent any override
		// Also prevent override in initialize() by checking if apply_sf_date is not set
		if (isset($atts['maximum_date']) && !empty($atts['maximum_date'])) {
			$max_date = date('Y-m-d', strtotime($atts['maximum_date']));
			$SKO->maximum_date = $max_date;
			$SKO->maximum_date_range = $max_date;
			
			// Also set in skin_options to ensure get_end_date() reads it correctly
			if (isset($SKO->skin_options) && is_array($SKO->skin_options)) {
				$skin_key = isset($atts['skin']) ? $atts['skin'] : 'list';
				if (!isset($SKO->skin_options[$skin_key])) {
					$SKO->skin_options[$skin_key] = array();
				}
				$SKO->skin_options[$skin_key]['maximum_date_range'] = $max_date;
			}
		}
		
		// Fetch the events
		$SKO->fetch();
		
		// Check if there are more events available beyond the current limit
		// This is needed to determine if Load More button should be shown
		$has_more_events = false;
		
		// Check if load_more_button is enabled (from atts or SKO)
		$load_more_enabled = false;
		if (isset($atts['load_more']) && ($atts['load_more'] === true || $atts['load_more'] === 'true' || $atts['load_more'] == '1')) {
			$load_more_enabled = true;
		} elseif (isset($SKO->load_more_button) && $SKO->load_more_button) {
			$load_more_enabled = true;
		}
		
		if ($load_more_enabled) {
			// Only show Load More button if found is GREATER than limit (not equal)
			// If found equals limit, we need to check if there are more events
			if ($SKO->found == $SKO->limit) {
				// Create a temporary query with limit+1 to check if there are more events
				$temp_atts = $atts;
				$temp_atts['limit'] = $SKO->limit + 1;
				$temp_atts['limit_events'] = $SKO->limit + 1;
				$temp_atts['offset'] = $SKO->offset;
				// Ensure speaker filter is maintained for the temporary query
				$temp_atts['speaker'] = $atts['id'];
				$temp_atts['from_advanced_speaker_addon'] = true;
				
				// Re-extract atts to ensure sk-options is properly set with new limit
				$temp_atts = MEC_Advanced_Speaker_Lib_Factory::extract_attrs($temp_atts, true, 'speaker');
				
				$temp_SKO = new $skin_class_name();
				$temp_SKO->skin = $atts['skin'];
				$temp_SKO->initialize($temp_atts);
				$temp_SKO->fetch();
				
				// If we found more than the original limit, there are more events available
				if ($temp_SKO->found > $SKO->limit) {
					$has_more_events = true;
				}
			} elseif ($SKO->found > $SKO->limit) {
				// If found is already more than limit, there are definitely more events
				$has_more_events = true;
			}
		}
		
		// Store has_more_events in SKO for use in template and get_pagination_bar()
		// This is used by MEC core's get_pagination_bar() method
		// Note: get_pagination_bar() checks found >= limit AND has_more_events
		// We only set has_more_events to true if found > limit (not equal)
		@$SKO->has_more_events = $has_more_events;

		$theme_path = get_template_directory() .DS. 'webnus' .DS. 'mec-advanced-speaker' . DS . 'skins' . DS;

		$custom_tpl_path = $theme_path . 'single.php';
		if( file_exists( $custom_tpl_path ) ) {

			$path = $custom_tpl_path;
		} else {

			$path = MEC_ADVANCED_SPEAKER_DIR . 'core' . DS . 'skins' . DS . 'single.php';
		}

		ob_start();
			$load_assets ? MEC_Advanced_Speaker_Lib_Factory::frontend_load_assets() : '';
			include $path;
		return ob_get_clean();

	}

	public static function speaker_list_content($atts = null, $content = '', $load_assets = true) {

		$atts = MEC_Advanced_Speaker_Lib_Factory::extract_attrs($atts, false, 'speaker');

		$skin = new MEC_Advanced_Speaker_Lib_Skin();
		$skin->section = 'speaker';

		// Initialize the skin
		$skin->initialize($atts);

		// Fetch the events
		$skin->fetch();
		ob_start();
			$load_assets ? MEC_Advanced_Speaker_Lib_Factory::frontend_load_assets() : '';
			echo $skin->output();
		return ob_get_clean();
	}

	public function load_more() {

		$skin = new MEC_Advanced_Speaker_Lib_Skin();
		$skin->dir = self::$dir;
		$skin->section = 'speaker';
		return $skin->load_more();
	}

	public static function speaker_featured_content($atts, $content = '', $load_assets = true) {

		if ($atts == null) {
			$atts = array();
		}

		$atts = MEC_Advanced_Speaker_Lib_Factory::extract_attrs($atts, false, 'speaker');
		$main = \MEC::getInstance('app.libraries.main');

		$main->load_owl_assets();

		$skin = new MEC_Advanced_Speaker_Lib_Skin();
		$skin->section = 'speaker';
		$atts['out_style'] = 'featured';

		// Initialize the skin
		$skin->initialize($atts);

		// Fetch the events
		$skin->fetch();

		$theme_path = get_template_directory() .DS. 'webnus' .DS. 'mec-advanced-speaker' . DS . 'skins' . DS;

		$custom_tpl_path = $theme_path . 'slider.php';
		if( file_exists( $custom_tpl_path ) ) {

			$path = $custom_tpl_path;
		} else {

			$path = MEC_ADVANCED_SPEAKER_DIR . 'core' . DS . 'skins' . DS . 'slider.php';
		}
		ob_start();
			$load_assets ? MEC_Advanced_Speaker_Lib_Factory::frontend_load_assets() : '';
			include $path;
		return ob_get_clean();
	}

}