<?php
/**
 * Microsoft Teams Shortcodes Handler
 *
 * @package SOVLIX\MHUB\MsTeams
 */

namespace SOVLIX\MHUB\MsTeams;

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

if ( ! class_exists( 'Mhub_MsTeams_Shortcodes' ) ) {
	/**
	 * Class Mhub_MsTeams_Shortcodes
	 *
	 * Handles Microsoft Teams shortcodes for displaying meetings.
	 */
	class Mhub_MsTeams_Shortcodes {
		/**
		 * Hold my instance.
		 *
		 * @var Mhub_MsTeams_Shortcodes|null
		 */
		protected static $instance;

		/**
		 * Create only one instance so that it may not Repeat
		 */
		public static function instance() {
			if ( is_null( self::$instance ) ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Mhub_MsTeams_Shortcodes constructor.
		 */
		public function __construct() {
			$this->register_shortcodes();
		}

		/**
		 * Register Microsoft Teams shortcodes.
		 */
		public function register_shortcodes() {
			// Kebab-case (Recommended)
			add_shortcode( 'mhub-msteams-meeting', array( $this, 'display_single_meeting' ) );
			add_shortcode( 'mhub-msteams-meeting-list', array( $this, 'display_meetings_list' ) );
			add_shortcode( 'mhub-msteams-registration', array( $this, 'display_registration_form' ) );
			add_shortcode( 'mhub-msteams-upcoming', array( $this, 'display_upcoming_meetings' ) );

			// Snake-case (Legacy/Aliases)
			add_shortcode( 'mhub_msteams_meeting', array( $this, 'display_single_meeting' ) );
			add_shortcode( 'mhub_msteams_meetings', array( $this, 'display_meetings_list' ) );
			add_shortcode( 'mhub_msteams_registration', array( $this, 'display_registration_form' ) );
			add_shortcode( 'mhub_msteams_upcoming', array( $this, 'display_upcoming_meetings' ) );
		}

		/**
		 * Display single Microsoft Teams meeting.
		 *
		 * @param array $atts Shortcode attributes.
		 * @return string
		 */
		public function display_single_meeting( $atts ) {
			if ( empty( $atts['id'] ) ) {
				return '<p>' . __( 'Meeting ID is required.', 'meetinghub' ) . '</p>';
			}

			$atts = shortcode_atts(
				array(
					'id'            => $atts['id'],
					'hide_details'  => isset( $atts['hide_details'] ) ? $atts['hide_details'] : 'no',
					'hide_timer'    => isset( $atts['hide_timer'] ) ? $atts['hide_timer'] : 'no',
					'hide_calendar' => mhub_fs()->can_use_premium_code__premium_only() && isset( $atts['hide_calendar'] ) ? $atts['hide_calendar'] : 'yes',
				),
				$atts,
				'mhub-msteams-meeting'
			);

			$meeting = get_post( intval( $atts['id'] ) );

			if ( ! $meeting || 'mhub_meeting' !== $meeting->post_type ) {
				return '<h1>' . esc_html__( 'The meeting has ended or does not exist.', 'meetinghub' ) . '</h1>';
			}

			$serialize_options = get_post_meta( $meeting->ID, 'mhub__meeting_settings', true );
			$options           = maybe_unserialize( $serialize_options );

			if ( empty( $options ) || 'msteams' !== $options['selected_platform'] ) {
				return '<p>' . __( 'This is not a Microsoft Teams meeting.', 'meetinghub' ) . '</p>';
			}

			ob_start();

			$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( $meeting->ID, 'mhub_meeting_status', true );
			$meeting_start_status = get_post_meta( $meeting->ID, 'mhub_meeting_start_status', true );
			$meeting_description  = get_post_meta( $meeting->ID, 'meeting_description', true );
			$thumbnail_html       = get_the_post_thumbnail( $meeting->ID );
			$meeting_title        = get_the_title( $meeting->ID );
			$time_zone            = isset( $options['meeting_timezone'] ) ? $options['meeting_timezone'] : 'UTC';
			$enable_user_zone     = isset( $options['display_time_user_zone'] ) ? $options['display_time_user_zone'] : '';

			$gmt_array       = mhub_get_gmt_offset( $time_zone );
			$gmt_offset_val  = $gmt_array['gmt_offset_val'];

			$po_meeting_id = $meeting->ID;
			$hide_details  = $atts['hide_details'];
			$hide_timer    = $atts['hide_timer'];
			$hide_calendar = $atts['hide_calendar'];

			$attendee_login = false;
			$should_register = isset( $options['enable_should_register'] ) ? $options['enable_should_register'] : false;

			if ( mhub_fs()->can_use_premium_code__premium_only() ) {
				$cookie_key   = "mhub_login_status_{$po_meeting_id}";
				$login_status = isset( $_COOKIE[ $cookie_key ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ $cookie_key ] ) ) : '';
				$attendee_login = 'login_successful' === $login_status ? true : false;
			}

			$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( $meeting->ID, 'mhub_msteams_meeting_duration', true );
			$join_link        = get_post_meta( $meeting->ID, 'mhub_msteams_join_url', true );
			$meeting_id_meta  = get_post_meta( $meeting->ID, 'mhub_msteams_meeting_id', true );

			$web_link = '';
			if ( class_exists( '\SOVLIX\MHUB\API\MsTeams_Api' ) ) {
				$msteams_api      = \SOVLIX\MHUB\API\MsTeams_Api::get_instance();
				$msteams_response = $msteams_api->get_meeting( $meeting_id_meta );

				// Fallback to saved details if API fails (e.g. for Personal accounts using Calendar API)
				if ( isset( $msteams_response['error'] ) || empty( $msteams_response ) ) {
					$saved_details = get_post_meta( $meeting->ID, 'mhub_msteams_details', true );
					if ( ! empty( $saved_details ) && ! isset( $saved_details['error'] ) ) {
						$msteams_response = $saved_details;
					}
				}

				$web_link = isset( $msteams_response['webLink'] ) ? $msteams_response['webLink'] : '';
			}

			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 ) );
			}

			?>
			<div class="meetinghub-wrapper" data-mhub-starttime="<?php echo esc_attr( $next_meeting_time ); ?>" data-mhub-timezone="<?php echo esc_attr( $time_zone ); ?>" data-mhub-title="<?php echo esc_attr( $meeting_title ); ?>" data-mhub-permalilk="<?php echo esc_url( get_permalink( $po_meeting_id ) ); ?>" data-mhub-enable-user-zone="<?php echo esc_attr( $enable_user_zone ); ?>">

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

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

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

				<div class="mhub-col-12" style="float: none;">
					<?php if ( 'end' !== $meeting_status ) : ?>
						<?php if ( ( $should_register && $attendee_login ) || current_user_can( 'manage_options' ) || ! $should_register ) : ?>
							<div class="mhub-msteams-st-join-links" style="margin-top: 20px; text-align: center;">
								<?php if ( ! empty( $join_link ) ) : ?>
									<a class="meetinghub-msteams-button mhub-msteams-join" target="_blank" href="<?php echo esc_url( $join_link ); ?>" title="JOIN NOW">
										<?php esc_html_e( 'JOIN MICROSOFT TEAMS MEETING', 'meetinghub' ); ?>
									</a>
								<?php elseif ( ! empty( $web_link ) ) : ?>
									<a class="meetinghub-msteams-button mhub-msteams-join" target="_blank" href="<?php echo esc_url( $web_link ); ?>" title="<?php esc_attr_e( 'View Calendar Event', 'meetinghub' ); ?>">
										<?php esc_html_e( 'VIEW IN CALENDAR', 'meetinghub' ); ?>
									</a>
									<?php if ( current_user_can( 'manage_options' ) ) : ?>
										<div class="meeting-not-started" style="margin-top: 10px;">
											<p style="margin: 0; font-size: 14px;"><?php esc_html_e( 'Admin Note: No video link generated. This happens with Personal (Free) accounts. To generate video links, please use a Microsoft 365 Business or Education account.', 'meetinghub' ); ?></p>
										</div>
									<?php endif; ?>
								<?php else : ?>
									<div class="meeting-not-started">
										<?php 
										if ( current_user_can( 'manage_options' ) ) {
											esc_html_e( 'No join link available. To generate video links, please use a Microsoft 365 Business or Education account.', 'meetinghub' ); 
										} else {
											esc_html_e( 'Meeting link not available yet.', 'meetinghub' );
										}
										?>
									</div>
								<?php endif; ?>
							</div>
						<?php else : ?>
							<?php
							if ( mhub_fs()->can_use_premium_code__premium_only() ) {
								require_once MHUB_PRO_INCLUDES . '/Templates/mhub-register.php';
							} else {
								echo '<p>' . esc_html__( 'Registration is required to join this meeting.', 'meetinghub' ) . '</p>';
							}
							?>
						<?php endif; ?>
					<?php else : ?>
						<div class="meeting-not-started">
							<?php esc_html_e( 'The meeting has ended by the host.', 'meetinghub' ); ?>
						</div>
					<?php endif; ?>
				</div>

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

									<dt><?php esc_html_e( 'Start Time:', 'meetinghub' ); ?></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:', 'meetinghub' ); ?></dt>
									<dd class="mhub-duration">
										<?php
										if ( 60 <= $meeting_duration ) {
											$hours   = floor( $meeting_duration / 60 );
											$minutes = $meeting_duration % 60;
											$hour_text   = ( 1 == $hours ) ? __( 'hour', 'meetinghub' ) : __( 'hours', 'meetinghub' );
											$minute_text = ( 1 == $minutes ) ? __( 'minute', 'meetinghub' ) : __( 'minutes', 'meetinghub' );
											echo esc_html( number_format_i18n( $hours ) ) . ' ' . esc_html( $hour_text );
											if ( $minutes > 0 ) {
												echo ' ' . esc_html( number_format_i18n( $minutes ) ) . ' ' . esc_html( $minute_text );
											}
										} else {
											$minute_text = ( 1 == $meeting_duration ) ? __( 'minute', 'meetinghub' ) : __( 'minutes', 'meetinghub' );
											echo esc_html( number_format_i18n( $meeting_duration ) ) . ' ' . esc_html( $minute_text );
										}
										?>
									</dd>

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

				<?php if ( 'yes' !== $hide_calendar && mhub_fs()->can_use_premium_code__premium_only() ) : ?>
					<div class="mhub-col-12" style="float: none; margin-top:40px;">
						<div class="mhub-sidebar">
							<?php require_once MHUB_PRO_INCLUDES . '/Templates/mhub-calander.php'; ?>
						</div>
					</div>
				<?php endif; ?>
			</div>
			<?php
			return ob_get_clean();
		}

		/**
		 * Display Microsoft Teams meetings list.
		 *
		 * @param array $atts Shortcode attributes.
		 * @return string
		 */
		/**
		 * Display Microsoft Teams meetings list.
		 *
		 * Supports the 'available' attribute: [mhub-msteams-meeting-list available="yes"]
		 * When set to 'yes', only upcoming / not-ended meetings are shown.
		 *
		 * @param array $atts Shortcode attributes.
		 * @return string
		 */
		public function display_meetings_list( $atts ) {
			$atts      = shortcode_atts( array( 'available' => '' ), (array) $atts, 'mhub-msteams-meeting-list' );
			$available = sanitize_text_field( $atts['available'] );

			ob_start();
			?>
			<div id="mhub_msteams_meeting_list"<?php echo ( in_array( strtolower( $available ), array( 'yes', 'true' ), true ) ) ? ' data-available="yes"' : ''; ?>></div>
			<?php
			return ob_get_clean();
		}

		/**
		 * Display Microsoft Teams meeting registration form.
		 *
		 * @param array $atts Shortcode attributes.
		 * @return string
		 */
		public function display_registration_form( $atts ) {
			if ( empty( $atts['id'] ) ) {
				return '<p>' . __( 'Meeting ID is required.', 'meetinghub' ) . '</p>';
			}

			$atts = shortcode_atts(
				array(
					'id'           => '',
					'redirect_url' => '',
				),
				$atts,
				'mhub-msteams-registration'
			);

			$meeting = get_post( intval( $atts['id'] ) );

			if ( ! $meeting || 'mhub_meeting' !== $meeting->post_type ) {
				return '<p>' . __( 'Meeting not found.', 'meetinghub' ) . '</p>';
			}

			$serialize_options = get_post_meta( $meeting->ID, 'mhub__meeting_settings', true );
			$options           = maybe_unserialize( $serialize_options );

			if ( empty( $options ) || 'msteams' !== $options['selected_platform'] ) {
				return '<p>' . __( 'This is not a Microsoft Teams meeting.', 'meetinghub' ) . '</p>';
			}

			$registration_enabled = isset( $options['enable_should_register'] ) ? $options['enable_should_register'] : false;
			if ( ! $registration_enabled ) {
				return '<p>' . __( 'Registration is not enabled for this meeting.', 'meetinghub' ) . '</p>';
			}

			ob_start();
			?>
			<div class="mhub-msteams-registration-form">
				<h3><?php esc_html_e( 'Register for Meeting', 'meetinghub' ); ?></h3>
				<form method="post" action="" class="msteams-registration-form">
					<?php wp_nonce_field( 'mhub_msteams_registration', 'msteams_registration_nonce' ); ?>
					<input type="hidden" name="meeting_id" value="<?php echo esc_attr( $meeting->ID ); ?>">
					<input type="hidden" name="redirect_url" value="<?php echo esc_url( $atts['redirect_url'] ); ?>">

					<div class="form-group">
						<label for="first_name"><?php esc_html_e( 'First Name', 'meetinghub' ); ?> *</label>
						<input type="text" id="first_name" name="first_name" required>
					</div>

					<div class="form-group">
						<label for="last_name"><?php esc_html_e( 'Last Name', 'meetinghub' ); ?> *</label>
						<input type="text" id="last_name" name="last_name" required>
					</div>

					<div class="form-group">
						<label for="email"><?php esc_html_e( 'Email Address', 'meetinghub' ); ?> *</label>
						<input type="email" id="email" name="email" required>
					</div>

					<div class="form-group">
						<label for="company"><?php esc_html_e( 'Company', 'meetinghub' ); ?></label>
						<input type="text" id="company" name="company">
					</div>

					<div class="form-actions">
						<button type="submit" name="msteams_register" class="mhub-register-button">
							<?php esc_html_e( 'Register Now', 'meetinghub' ); ?>
						</button>
					</div>
				</form>
			</div>
			<?php
			return ob_get_clean();
		}

		/**
		 * Display upcoming Microsoft Teams meetings.
		 *
		 * @param array $atts Shortcode attributes.
		 * @return string
		 */
		public function display_upcoming_meetings( $atts ) {
			ob_start();
			?>
			<div id="mhub_msteams_upcoming_list"></div>
			<?php
			return ob_get_clean();
		}
	}

}