<?php // phpcs:ignore
/**
 * Wemeet_Shortcodes Class
 *
 * This class manages the frontend functionality for the Meeting Hub plugin.
 *
 * @package SOVLIX\WEMEET
 */

namespace SOVLIX\WEMEET;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Wemeet_Shortcodes' ) ) {
	/**
	 * Wemeet_Shortcodes Class
	 *
	 * Handles frontend-related tasks and functionality for the Meeting Hub plugin.
	 *
	 * @since 1.0.0
	 */
	class Wemeet_Shortcodes {
		/**
		 * Webex Api class.
		 *
		 * @var Wemeet_Webex_Api
		 */
		private $webex_api;

		/**
		 * Wemeet_Shortcodes constructor.
		 *
		 * Initializes the frontend class.
		 */
		public function __construct() {
			$this->webex_api = \SOVLIX\WEMEET\API\Webex_Api::get_instance();
			add_shortcode( 'wemeet-webex-meeting', array( $this, 'wemeet_webex_shortcode_render' ) );
			add_shortcode( 'wemeet-webex-meeting-list', array( $this, 'wemeet_webex_meeting_list_shortcode_render' ) );
		}

		/**
		 * Renders the Webex meeting details using a shortcode.
		 *
		 * This function processes the shortcode attributes, retrieves relevant
		 * meeting information from the post meta, and generates HTML to display
		 * the meeting details and join link. It handles both the Pro and Free
		 * versions of the plugin, checks the meeting status, and manages user
		 * authentication and registration if required.
		 *
		 * @param array $atts {
		 *     Optional. An array of shortcode attributes.
		 *
		 *     @type int $id The ID of the post containing the meeting settings. Default is the current post ID.
		 * }
		 * @return string The HTML content for displaying the Webex meeting details.
		 */
		public function wemeet_webex_shortcode_render( $atts ) {
			$is_available  = false;
			if ( ! empty( $atts ) ) {
				// Extract shortcode attributes, including the 'id' attribute if provided.
				$atts = shortcode_atts(
					array(
						'id'            => $atts['id'],
						'hide_details'  => $atts['hide_details'],
						'hide_timer'    => $atts['hide_timer'],
						'hide_calendar' => $is_available ? $atts['hide_calendar'] : '',
					),
					$atts,
					'wemeet-webex-meeting'
				);

				// Check if the post exists.
				if ( ! get_post_status( $atts['id'] ) ) {
					return '<h1>' . esc_html__( 'The meeting has ended or does not exist.', 'wemeet' ) . '</h1>';
				}

				ob_start();

				$serialize_options = get_post_meta( $atts['id'], 'wemeet__meeting_settings', true );
				$options           = maybe_unserialize( $serialize_options );

				$user_id           = get_current_user_id();
				$current_user_data = get_userdata( $user_id );
				$current_user_name = $current_user_data ? $current_user_data->display_name : '';

				$meeting_status       = get_post_meta( $atts['id'], 'wemeet_meeting_status', true );
				$meeting_start_status = get_post_meta( $atts['id'], 'wemeet_meeting_start_status', true );
				$meeting_description  = get_post_meta( $atts['id'], 'meeting_description', true );
				$thumbnail_html       = get_the_post_thumbnail( $atts['id'] );
				$meeting_title        = get_the_title( $atts['id'] );
				$hide_sidebar         = $options['hide_sidebar'];
				$time_zone            = $options['meeting_timezone'];
				$enable_user_zone     = isset( $options['display_time_user_zone'] ) ? $options['display_time_user_zone'] : '';

				$gmt_array       = wemeet_get_gmt_offset( $options['meeting_timezone'] );
				$gmt_offset_val  = $gmt_array['gmt_offset_val'];
				$gmt_offset      = $gmt_array['gmt_offset'];
				$should_register = false;
				$attendee_login  = false;
				$login_status;
				$meeting_as_product;
				$product_id;
				$po_meeting_id = $atts['id'];
				$hide_details  = $atts['hide_details'];
				$hide_timer    = $atts['hide_timer'];
				$hide_calendar = $atts['hide_calendar'];

				if ( $is_available ) {
					$cookie_key         = "wemeet_login_status_{$po_meeting_id}";
					$login_status       = isset( $_COOKIE[ $cookie_key ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ $cookie_key ] ) ) : '';
					$meeting_as_product = get_post_meta( $atts['id'], 'wemeet_connect_as_product', true );
					$product_id         = get_post_meta( $atts['id'], 'wemeet_connect_product_id', true );
					$should_register    = isset( $options['enable_should_register'] ) ? $options['enable_should_register'] : false;
				}

				// Use the specified or default post ID to get the post meta.

				$is_schedule       = false;
				$next_meeting_time = '';

				$start_time       = gmdate( 'Y-m-d\TH:i:s.v\Z', strtotime( $options['startDateTime'] ) + $gmt_offset_val );
				$meeting_duration = get_post_meta( $atts['id'], 'wemeet_webex_meeting_duration', true );
				$join_link        = get_post_meta( $atts['id'], 'wemeet_webex_join_link', true );
				$meeting_agenda   = $options['agenda'];
				$meeting_id       = get_post_meta( $atts['id'], 'wemeet_webex_meeting_id', true );

				$webex_api        = \SOVLIX\WEMEET\API\Webex_Api::get_instance();
				$webex_response   = $webex_api->get_meeting( $meeting_id );
				$response_message = '';

				if ( isset( $webex_response['errors'] ) ) {
					$response_message = $webex_response['errors'][0]['description'];
				}

				if ( ( strtotime( gmdate( 'Y-m-d H:i:s' ) ) + $gmt_offset_val ) - strtotime( $start_time ) <= 0 ) {
					$next_meeting_time = gmdate( 'Y-m-d\TH:i:s.v\Z', strtotime( $start_time ) - $gmt_offset_val );
					$is_schedule       = true;
				} else {
					$next_meeting_time = gmdate( 'Y-m-d\TH:i:s.v\Z', strtotime( $start_time ) );
				}

				if ( $is_available ) {
					$attendee_login = 'login_successful' === $login_status ? true : false;
				}

				?>
					<div class="wemeet-wrapper" data-wemeet-starttime="<?php echo esc_attr( $next_meeting_time ); ?>" data-wemeet-timezone="<?php echo esc_attr( $options['meeting_timezone'] ); ?>" data-wemeet-title="<?php echo esc_attr( $meeting_title ); ?>" data-wemeet-permalilk="<?php echo esc_url( get_permalink( $po_meeting_id ) ); ?>" data-wemeet-enable-user-zone="<?php echo esc_attr( $enable_user_zone ); ?>">

						<div class="wemeet-col-12" style="float: none;">
							<?php
							if ( ! empty( $thumbnail_html ) ) {
								?>
									<div class="meeting-thumbnail">
										<?php echo wp_kses_post( $thumbnail_html ); ?>
									</div>
								<?php
							}
							?>

							<?php
							if ( ! empty( $meeting_description ) ) {
								?>
									<div class="meeting-details">
										<?php echo wp_kses_post( $meeting_description ); ?>
									</div>
								<?php
							}
							?>
						</div>

						<?php if ( 'yes' !== $hide_timer ) { ?>
						<div class="wemeet-col-12" style="float: none;">
							<div class="wemeet-webex-shortcode-sidebar">
								<div class="wemeet-single-widget wemeet-single-widget-countdown wemeet-shortcode-widget">
									<h4 class="wemeet-widget-title" style="margin:0; color:#fff;"><?php esc_html_e( 'Time to go', 'wemeet' ); ?></h4>
									<div class="wemeet-widget-inner">
										<?php if ( ! isset( $webex_response['errors'] ) ) { ?>
											<?php if ( 'end' !== $meeting_status ) { ?>
												<?php if ( $is_schedule ) { ?>
													<div class="wemeet_start_time" data-meeting-start-time="<?php echo esc_attr( $next_meeting_time ); ?>" data-meeting-time-offset="<?php echo esc_attr( $gmt_offset_val ); ?>" > </div>
													<?php } else { ?>
														<span class="wemeet-countdown-wrapper">
															<span class="wemeet-countdown-value"><?php esc_html_e( 'Meeting is running', 'wemeet' ); ?></span>
															<span class="wemeet-countdown-label"><?php esc_html_e( 'The meeting is started and running', 'wemeet' ); ?></span>
														</span>
													<?php } ?>
											<?php } else { ?>
												<span class="wemeet-countdown-wrapper">
													<span class="wemeet-countdown-value"><?php esc_html_e( 'Meeting is finished', 'wemeet' ); ?></span>
													<span class="wemeet-countdown-label"><?php esc_html_e( 'This meeting has been ended by the host.', 'wemeet' ); ?></span>
												</span>
											<?php } ?>
										<?php } else { ?>
											<span class="wemeet-countdown-wrapper">
													<span class="wemeet-countdown-label"><?php echo esc_html( $response_message ); ?></span>
											</span>

										<?php } ?>
									</div>
								</div>
							</div>
						</div>
						<?php } ?>

						<div class="wemeet-col-12" style="float: none;">
							<?php if ( ! isset( $webex_response['errors'] ) ) { ?>
								<?php if ( 'end' !== $meeting_status ) { ?>
									<?php if ( ( $should_register && $attendee_login ) || current_user_can( 'manage_options' ) || ! $should_register ) { ?>
										<?php if ( ! empty( $meeting_agenda ) ) { ?>
										<h3 class="webex-agenda-title"><?php esc_html_e( 'Meeting agenda', 'wemeet' ); ?> </h3>
										<p class="webex-agenda-desc"><?php echo esc_html( $meeting_agenda ); ?></p>
									<?php } ?>

									<div class="wemeet-webex-st-join-links">
										<a class="wemeet-webex-button wemeet-webex-join" target="_blank" href="<?php echo esc_url( $join_link ); ?>" title="JOIN NOW"><?php esc_html_e( 'JOIN NOW', 'wemeet' ); ?></a>
									</div>

										<?php
									} else {
										require_once WEMEET_PRO_INCLUDES . '/Templates/wemeet-register.php';
									}
									?>
							<?php } else { ?>
										<div class="meeting-not-started">
											<?php esc_html_e( 'The meeting has ended by the host.', 'wemeet' ); ?>
										</div>
									<?php } ?>
									<?php } else { ?>
										<div class="meeting-not-started">
											<?php echo esc_html( $response_message ); ?>
										</div>

								<?php } ?>
						</div>

						<?php if ( 'yes' !== $hide_details ) { ?>
						<div class="wemeet-col-12" style="float: none;">
							<div class="wemeet-sidebar">
								<div class="wemeet-single-widget wemeet-single-widget-detail">
									<h4 class="wemeet-widget-title" style="margin:0; color:#fff;"><?php esc_html_e( 'Details', 'wemeet' ); ?></h4>
									<div class="wemeet-widget-inner">
										<dl>
											<dt><?php esc_html_e( 'Topic:', 'wemeet' ); ?></dt>
											<dd><?php echo esc_html( the_title() ); ?></dd>
											<dt><?php esc_html_e( 'Hosted By:', 'wemeet' ); ?></dt>
											<dd>
											<?php
												echo esc_html( $current_user_name );
											?>
											</dd>

											<dt><?php esc_html_e( 'Start Time:', 'wemeet' ); ?></dt>
											<dd class="mhbu-tm">
											<?php

											echo esc_html( gmdate( 'l, F j, Y g:i A', strtotime( $start_time ) ) );

											?>
											</dd>

											<dt><?php esc_html_e( 'Duration:', 'wemeet' ); ?></dt>
											<dd class="wemeet-duration">
												<?php
												if ( 60 <= $meeting_duration ) {
													$hours   = floor( $meeting_duration / 60 );
													$minutes = $meeting_duration % 60;

													// Get the correct translation for "hour" or "hours".
													$hour_text   = ( 1 == $hours ) ? __( 'hour', 'wemeet' ) : __( 'hours', 'wemeet' );
													$minute_text = ( 1 == $minutes ) ? __( 'minute', 'wemeet' ) : __( 'minutes', 'wemeet' );

													// Print hours.
													echo esc_html( number_format_i18n( $hours ) ) . ' ' . esc_html( $hour_text );

													// Print minutes if greater than 0.
													if ( $minutes > 0 ) {
														echo ' ' . esc_html( number_format_i18n( $minutes ) ) . ' ' . esc_html( $minute_text );
													}
												} else {
													// Get the correct translation for "minute" or "minutes".
													$minute_text = ( 1 == $meeting_duration ) ? __( 'minute', 'wemeet' ) : __( 'minutes', 'wemeet' );

													// Print minutes only.
													echo esc_html( number_format_i18n( $meeting_duration ) ) . ' ' . esc_html( $minute_text );
												}
												?>
											</dd>

											<dt><?php esc_html_e( 'Current Timezone:', 'wemeet' ); ?></dt>
											<dd class="wemeet-tz">
											<?php
												echo esc_html( $time_zone );
											?>
											</dd>
											
										</dl>
									</div>
								</div>

								<div class="wemeet-buy-btn-wpapper">
									<?php
									if ( ! empty( $product_id ) && 'yes' === $meeting_as_product && ! current_user_can( 'manage_options' ) ) {
										$product_link = get_permalink( $product_id );
										?>
										<a href="<?php echo esc_url( $product_link ); ?>" class="wemeet-buy-button" target="__blank"> <?php esc_attr_e( 'Buy Now !', 'wemeet' ); ?></a>
									
									<?php } ?>
								</div>
							</div>
						</div>
						<?php } ?>

						<?php
						if ( 'yes' !== $hide_calendar ) {
							if ( $is_available ) {
								?>
								<div class="wemeet-col-12" style="float: none; margin-top:40px;">
									<div class="wemeet-sidebar">
								<?php
									require_once WEMEET_PRO_INCLUDES . '/Templates/wemeet-calander.php';
								?>
									</div>
								</div>
								<?php
							}
						}
						?>
				<?php
			} else {
				?>
				<h1> <?php echo esc_html__( 'Please use correct shortcode', 'wemeet' ); ?></h1>
				<?php
			}

			return ob_get_clean();
		}

		/**
		 * Renders the Webex meeting list shortcode.
		 *
		 * This function starts output buffering, prints the container for the Webex meeting list,
		 * and then returns the buffered content.
		 *
		 * @return string The buffered output of the Webex meeting list container.
		 */
		public function wemeet_webex_meeting_list_shortcode_render() {
			ob_start();

			?>
			<div id="wemeet_webex_meeting_list">
			</div>
			
			<?php

			return ob_get_clean();
		}
	}
}
