<?php // phpcs:ignore
/**
 * Goodmeet_Shortcodes Class
 *
 * This class manages the frontend functionality for the goodmeet plugin.
 *
 * @package SOVLIX\GOODMEET
 */

namespace SOVLIX\GOODMEET;

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

if ( ! class_exists( 'Goodmeet_Shortcodes' ) ) {
	/**
	 * Goodmeet_Shortcodes Class
	 *
	 * Handles frontend-related tasks and functionality for the goodmeet plugin.
	 *
	 * @since 1.0.0
	 */
	class Goodmeet_Shortcodes {

		/**
		 * Goodmeet_Shortcodes constructor.
		 *
		 * Initializes the frontend class.
		 */
		public function __construct() {
			add_shortcode( 'goodmeet-google-meeting', array( $this, 'goodmeet_google_meet_shortcode_render' ) );
			add_shortcode( 'goodmeet-google-meeting-list', array( $this, 'goodmeet_google_meeting_list_shortcode_render' ) );
		}

		/**
		 * Renders the Google 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 goodmeet_google_meet_shortcode_render( $atts ) {
			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' => goodmeet_fs()->can_use_premium_code__premium_only() ? $atts['hide_calendar'] : '',
					),
					$atts,
					'goodmeet-google-meet'
				);

				ob_start();

				$serialize_options = get_post_meta( $atts['id'], 'goodmeet__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'], 'goodmeet_meeting_status', true );
				$meeting_start_status = get_post_meta( $atts['id'], 'goodmeet_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       = goodmeet_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 ( goodmeet_fs()->can_use_premium_code__premium_only() ) {
					$cookie_key         = "goodmeet_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'], 'goodmeet_connect_as_product', true );
					$product_id         = get_post_meta( $atts['id'], 'goodmeet_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       = '';
				$meeting_duration = get_post_meta( $atts['id'], 'goodmeet_google_meeting_duration', true );
				$join_link        = get_post_meta( $atts['id'], 'goodmeet_google_join_link', true );
				$meeting_id       = get_post_meta( $atts['id'], 'goodmeet_google_meeting_id', true );
				$recurrence_info  = '';
				$recurrence_data  = null;

				if ( $options['enable_recurring_meeting'] && goodmeet_fs()->can_use_premium_code__premium_only() && function_exists( 'goodmeet_get_next_meeting_occurrence' ) ) {
					$recurrence_data = goodmeet_get_next_meeting_occurrence( $meeting_id, $atts['id'], $options );
				}

				if ( $options['enable_recurring_meeting'] && goodmeet_fs()->can_use_premium_code__premium_only() && function_exists( 'goodmeet_get_next_meeting_occurrence' ) ) {
					$recurrence_info = goodmeet_pro_get_recurrence_description( $options );
					if ( ! empty( $recurrence_data ) && ! empty( $recurrence_data['next_occurrence'] ) ) {
						$datetime = new \DateTime( $recurrence_data['next_occurrence'] );
						// Get the timestamp with correct timezone handling.
						$start_time        = $datetime->format( 'Y-m-d\TH:i:s.v\Z' );
						$next_meeting_time = $recurrence_data['next_occurrence'];
						$gmt_offset_val    = $recurrence_data['recurring_gmt_offset_val'];
					} else {
						$start_time = gmdate( 'Y-m-d\TH:i:s.v\Z', strtotime( $options['startDateTime'] ) + $gmt_offset_val );
						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 ) );
						}
					}
				} else {
					$start_time = gmdate( 'Y-m-d\TH:i:s.v\Z', strtotime( $options['startDateTime'] ) + $gmt_offset_val );

					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 ( goodmeet_fs()->can_use_premium_code__premium_only() ) {
					$attendee_login = 'login_successful' === $login_status ? true : false;
				}

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

						<div class="goodmeet-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="goodmeet-col-12" style="float: none;">
							<div class="goodmeet-google-meet-shortcode-sidebar">
								<div class="goodmeet-single-widget goodmeet-single-widget-countdown goodmeet_shortcode-widget">
									<h4 class="goodmeet-widget-title" style="margin:0; color:#fff;"><?php esc_html_e( 'Time to go', 'goodmeet' ); ?></h4>
									<div class="goodmeet-widget-inner">
										<?php if ( 'end' !== $meeting_status ) { ?>
											<?php if ( $is_schedule ) { ?>
												<div class="goodmeet-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="goodmeet-countdown-wrapper">
														<span class="goodmeet-countdown-value"><?php esc_html_e( 'Meeting is running', 'goodmeet' ); ?></span>
														<span class="goodmeet-countdown-label"><?php esc_html_e( 'The meeting is started and running', 'goodmeet' ); ?></span>
													</span>
												<?php } ?>
										<?php } else { ?>
											<span class="goodmeet-countdown-wrapper">
												<span class="goodmeet-countdown-value"><?php esc_html_e( 'Meeting is finished', 'goodmeet' ); ?></span>
												<span class="goodmeet-countdown-label"><?php esc_html_e( 'This meeting has been ended by the host.', 'goodmeet' ); ?></span>
											</span>
										<?php } ?>
									</div>
								</div>
							</div>
						</div>
						<?php } ?>

						<div class="goodmeet-col-12" style="float: none;">
							<?php if ( 'end' !== $meeting_status ) { ?>
								<?php if ( ( $should_register && $attendee_login ) || current_user_can( 'manage_options' ) || ! $should_register ) { ?>
									<?php
									if ( ! empty( $meeting_description ) ) {
										?>
											<div class="meeting-details">
												<?php echo wp_kses_post( $meeting_description ); ?>
											</div>
										<?php
									}
									?>

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

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

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

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

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

											?>
											</dd>

											<?php if ( $options['enable_recurring_meeting'] && goodmeet_fs()->can_use_premium_code__premium_only() ) { ?>
											<dt><?php esc_html_e( 'Meeting recurrence:', 'goodmeet' ); ?></dt>
											<dd> <?php echo esc_html( $recurrence_info ); ?> </dd>
											<?php } ?>

											<dt><?php esc_html_e( 'Duration:', 'goodmeet' ); ?></dt>
											<dd class="goodmeet-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', 'goodmeet' ) : __( 'hours', 'goodmeet' );
													$minute_text = ( 1 === $minutes ) ? __( 'minute', 'goodmeet' ) : __( 'minutes', 'goodmeet' );
													// 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 === (int) $meeting_duration ) ? __( 'minute', 'goodmeet' ) : __( 'minutes', 'goodmeet' );

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

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

								<div class="goodmeet-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="goodmeet-buy-button" target="__blank"> <?php esc_attr_e( 'Buy Now !', 'goodmeet' ); ?></a>
									
									<?php } ?>
								</div>
							</div>
						</div>
						<?php } ?>

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

			return ob_get_clean();
		}

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

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

			return ob_get_clean();
		}
	}
}
