<?php
/**
 * ZooMeet Functions
 *
 * @package ZMEET
 * @version 1.0.0
 */

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

if ( ! function_exists( 'zmeet_delete_meeting' ) ) {
	/**
	 * Delete Meeting
	 *
	 * @param int $id Delete Id.
	 *
	 * @return int|boolean
	 *
	 * @since 1.0.0
	 */
	function zmeet_delete_meeting( $id ) {
		delete_post_meta( $id, 'zmeet__meeting_settings', null );
		$deleted = wp_delete_post( $id );
		return $deleted;
	}
}


if ( ! function_exists( 'zmeet_meetings' ) ) {
	/**
	 * Fetch all Zoom meetings
	 *
	 * @return array
	 *
	 * @since 1.0.0
	 */
	function zmeet_meetings() {

		$user_id = get_current_user_id();

		$args = array(
			'post_type'      => 'zmeet_meeting',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
		);

		// If the user does not have the manage_options capability, limit the query to their own meetings.
		if ( ! current_user_can( 'manage_options' ) ) {
			$args['author'] = $user_id;
		}

		$wp_query = new \WP_Query( $args );
		$results  = $wp_query->posts;

		$meetings = array();

		foreach ( $results as $result ) {
			$meeting         = array();
			$settings        = get_post_meta( $result->ID, 'zmeet__meeting_settings', true );
			$settings        = maybe_unserialize( $settings );
			$settings['url'] = get_permalink( $result->ID );

			$meeting['id']       = $result->ID;
			$meeting['title']    = $result->post_title;
			$meeting['settings'] = $settings;
			$meeting['date']     = $result->post_date;
			$meetings[]          = $meeting;

		}

		wp_reset_postdata();

		return $meetings;
	}

	/**
	 * Get meetings by visibility mode.
	 * 
	 * @param string $mode Visibility mode (user, role, all).
	 * @param int $page_id The ID of the page where the shortcode is used.
	 * @param array $roles Selected roles for visibility.
	 * @param array $users Selected users for visibility.
	 * @param bool $use_passed_values Whether to use passed roles/users or get them from post meta.
	 * @return array List of meeting data.
	 */
	function zmeet_meetings_by_mode( $mode = 'user', $page_id = 0, $roles = array(), $users = array(), $use_passed_values = false ) {
		$args = array(
			'post_type'      => 'zmeet_meeting',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
		);

		if ( 'role' === $mode ) {
			if ( ! $use_passed_values && empty( $roles ) && $page_id ) {
				$roles = get_post_meta( $page_id, '_zmeet_visibility_roles', true );
				if ( ! $roles ) {
					$roles = array();
				}
			}

			if ( ! empty( $roles ) ) {
				$role_users = get_users(
					array(
						'role__in' => $roles,
						'fields'   => array( 'ID' ),
					)
				);

				$user_ids = array_map(
					function ( $user ) {
						return $user->ID;
					},
					$role_users
				);

				if ( ! empty( $user_ids ) ) {
					$args['author__in'] = $user_ids;
				} else {
					$args['author__in'] = array( 0 ); // Return no posts.
				}
			} else {
				$args['author__in'] = array( 0 );
			}
		} elseif ( 'user' === $mode ) {
			if ( ! $use_passed_values && empty( $users ) && $page_id ) {
				$users = get_post_meta( $page_id, '_zmeet_visibility_users', true );
				if ( ! $users ) {
					$users = array();
				}
			}

			if ( ! empty( $users ) ) {
				$args['author__in'] = array_map( 'absint', $users );
			} else {
				$args['author__in'] = array( 0 );
			}
		}

		$wp_query = new \WP_Query( $args );
		$meetings = array();

		foreach ( $wp_query->posts as $post ) {
			$settings = maybe_unserialize( get_post_meta( $post->ID, 'zmeet__meeting_settings', true ) );

			if ( ! is_array( $settings ) ) {
				$settings = array();
			}

			$settings['url'] = get_permalink( $post->ID );

			$meetings[] = array(
				'id'       => $post->ID,
				'title'    => $post->post_title,
				'date'     => $post->post_date,
				'settings' => $settings,
			);
		}

		wp_reset_postdata();
		return $meetings;
	}

}


if ( ! function_exists( 'zmeet_meeting' ) ) {

	/**
	 * Fetch a single meeting from the DB
	 *
	 * @param int $id Meeting Id.
	 *
	 * @return object
	 *
	 * @since 1.0.0
	 */
	function zmeet_meeting( $id ) {
		$meeting = array();

		$post                = get_post( $id );
		$settings            = get_post_meta( $id, 'zmeet__meeting_settings', true );
		$meeting_description = get_post_meta( $id, 'meeting_description', true );

		$meeting['id']                  = $post->ID;
		$meeting['title']               = $post->post_title;
		$meeting['settings']            = maybe_unserialize( $settings );
		$meeting['meeting_description'] = $meeting_description;
		$meeting['date']                = $post->post_date;

		return $meeting;
	}
}


if ( ! function_exists( 'zmeet_prepare_zoom_meeting_data' ) ) {
	/**
	 * Prepare data for creating a Zoom meeting.
	 *
	 * This function prepares data required for creating a Zoom meeting based on the provided parameters.
	 *
	 * @param string $title The title of the meeting.
	 * @param array  $meeting_settings The settings for the meeting, including start date, agenda, timezone, etc.
	 * @param int    $duration The duration of the meeting in minutes.
	 *
	 * @return array The prepared meeting data including topic, agenda, start time, timezone, password, duration, and settings.
	 */
	function zmeet_prepare_zoom_meeting_data( $title, $meeting_settings, $duration ) {
		$start_time           = $meeting_settings['startDateTime'];
		$alternative_host_ids = '';

		// Create a DateTime object from the given string.
		$datetime = new DateTime( $start_time );

		// Set the time zone to UTC.
		$datetime->setTimezone( new DateTimeZone( 'UTC' ) );

		// Format the date and time to ISO 8601 format in UTC.
		$utc_time = $datetime->format( 'Y-m-d\TH:i:s\Z' );

		if ( ! empty( $meeting_settings['alternative_host'] ) ) {
			$alternative_host_arr = array();

			foreach ( $meeting_settings['alternative_host'] as $meeting_host ) {
				$alternative_host_arr[] = $meeting_host->value;
			}

			if ( count( $alternative_host_arr ) > 1 ) {
				$alternative_host_ids = implode( ',', $alternative_host_arr );
			} else {
				$alternative_host_ids = $alternative_host_arr[0];
			}
		}

		$meeting_arr = array(
			'topic'      => $title,
			'agenda'     => ! empty( $meeting_settings['agenda'] ) ? $meeting_settings['agenda'] : '',
			'start_time' => $utc_time,
			'timezone'   => $meeting_settings['meeting_timezone'],
			'password'   => ! empty( $meeting_settings['password'] ) ? $meeting_settings['password'] : false,
			'duration'   => $duration,
			'settings'   => array(
				'meeting_authentication' => ! empty( $meeting_settings['meeting_authentication'] ) ? true : false,
				'join_before_host'       => ! empty( $meeting_settings['join_before_host'] ) ? true : false,
				'host_video'             => ! empty( $meeting_settings['option_host_video'] ) ? true : false,
				'participant_video'      => ! empty( $meeting_settings['option_participants_video'] ) ? true : false,
				'mute_upon_entry'        => ! empty( $meeting_settings['option_mute_participants'] ) ? true : false,
				'auto_recording'         => ! empty( $meeting_settings['auto_recording'] ) ? $meeting_settings['auto_recording'] : 'none',
				'alternative_hosts'      => isset( $alternative_host_ids ) ? $alternative_host_ids : '',
				'waiting_room'           => isset( $meeting_settings['disable_waiting_room'] ) && ( 'yes' === $meeting_settings['disable_waiting_room'] ) ? false : true,
			),
		);

		return $meeting_arr;
	}
}

if ( ! function_exists( 'zmeet_prepare_webinar' ) ) {
	/**
	 * Prepare data for creating a Zoom webinar.
	 *
	 * This function prepares data required for creating a Zoom webinar based on the provided parameters.
	 *
	 * @param string $title The title of the webinar.
	 * @param array  $meeting_settings The settings for the webinar, including start date, agenda, timezone, etc.
	 * @param int    $duration The duration of the webinar in minutes.
	 *
	 * @return array The prepared webinar data including topic, agenda, start time, timezone, password, duration, and settings.
	 */
	function zmeet_prepare_webinar( $title, $meeting_settings, $duration ) {
		$start_time           = $meeting_settings['startDateTime'];
		$alternative_host_ids = '';

		// Create a DateTime object from the given string.
		$datetime = new DateTime( $start_time );

		// Set the time zone to UTC.
		$datetime->setTimezone( new DateTimeZone( 'UTC' ) );

		// Format the date and time to ISO 8601 format in UTC.
		$utc_time = $datetime->format( 'Y-m-d\TH:i:s\Z' );

		if ( ! empty( $meeting_settings['alternative_host'] ) ) {
			$alternative_host_arr = array();

			foreach ( $meeting_settings['alternative_host'] as $meeting_host ) {
				$alternative_host_arr[] = $meeting_host->value;
			}

			if ( count( $alternative_host_arr ) > 1 ) {
				$alternative_host_ids = implode( ',', $alternative_host_arr );
			} else {
				$alternative_host_ids = $alternative_host_arr[0];
			}
		}

		$webinar_arrr = array(
			'topic'      => $title,
			'agenda'     => ! empty( $meeting_settings['agenda'] ) ? $meeting_settings['agenda'] : '',
			'start_time' => $utc_time,
			'timezone'   => $meeting_settings['meeting_timezone'],
			'password'   => ! empty( $meeting_settings['password'] ) ? $meeting_settings['password'] : false,
			'duration'   => $duration,
			'settings'   => array(
				'host_video'             => ! empty( $meeting_settings['option_host_video'] ) ? true : false,
				'panelists_video'        => ! empty( $meeting_settings['panelists_video'] ) ? true : false,
				'practice_session'       => ! empty( $meeting_settings['practice_session'] ) ? true : false,
				'hd_video'               => ! empty( $meeting_settings['hd_video'] ) ? true : false,
				'allow_multiple_devices' => ! empty( $meeting_settings['allow_multiple_devices'] ) ? true : false,
				'alternative_hosts'      => isset( $alternative_host_ids ) ? $alternative_host_ids : '',
				'auto_recording'         => ! empty( $meeting_settings['auto_recording'] ) ? $meeting_settings['auto_recording'] : 'none',
			),
		);

		return $webinar_arrr;
	}
}


if ( ! function_exists( 'zmeet_is_server_auth_prepare' ) ) {
	/**
	 * Check if the server authentication for Zoom is prepared by verifying the presence
	 * of OAuth account ID, OAuth client ID, and OAuth client secret in the Zoom settings.
	 *
	 * @return bool Whether the server authentication is prepared or not.
	 */
	function zmeet_is_server_auth_prepare() {
		$status = false;

		// Get Zoom settings from options.
		$zoom_settings = get_option( 'zmeet_zoom_settings' );

		if ( is_array( $zoom_settings ) && ! empty( $zoom_settings ) ) {
			// Extract API key and API secret from settings.
			$account_id    = isset( $zoom_settings['oauth_account_id'] ) ? $zoom_settings['oauth_account_id'] : '';
			$client_id     = isset( $zoom_settings['oauth_client_id'] ) ? $zoom_settings['oauth_client_id'] : '';
			$client_secret = isset( $zoom_settings['oauth_client_secret'] ) ? $zoom_settings['oauth_client_secret'] : '';

			// Check if API key is not empty and API secret is empty.
			if ( ! empty( $account_id ) && ! empty( $client_id ) && ! empty( $client_secret ) ) {
				update_option( 'zmeet_is_server_auth_prepare', 'yes' );
				$status = true;
			} else {
				update_option( 'zmeet_is_server_auth_prepare', 'no' );
			}
		}

		return $status;
	}

}


if ( ! function_exists( 'zmeet_is_zoom_oauth_connected' ) ) {
	/**
	 * Check if Zoom OAuth is connected.
	 *
	 * @return bool
	 */
	function zmeet_is_zoom_oauth_connected() {
		$oauth_data = get_option( 'zmeet_zoom_global_oauth_data' );
		return ! empty( $oauth_data ) && zmeet_is_server_auth_prepare();
	}
}

if ( ! function_exists( 'zmeet_is_sdk_prepare' ) ) {
	/**
	 * Check if Zoom SDK is prepared.
	 *
	 * @return bool
	 */
	function zmeet_is_sdk_prepare() {
		$zoom_settings = get_option( 'zmeet_zoom_settings' );
		if ( is_array( $zoom_settings ) && ! empty( $zoom_settings ) ) {
			$client_id     = isset( $zoom_settings['sdk_client_id'] ) ? $zoom_settings['sdk_client_id'] : '';
			$client_secret = isset( $zoom_settings['sdk_client_secret'] ) ? $zoom_settings['sdk_client_secret'] : '';
			return ! empty( $client_id ) && ! empty( $client_secret );
		}
		return false;
	}
}


if ( ! function_exists( 'zmeet_timezone_offset' ) ) {
	/**
	 * Retrieve the timezone offset in hours and minutes.
	 *
	 * This function fetches the timezone offset from WordPress options. If the offset is empty,
	 * it defaults to 'UTC'. The offset is returned in the format specified by WordPress options.
	 *
	 * @return string The timezone offset in hours and minutes.
	 */
	function zmeet_timezone_offset() {
		$fetched_offset = get_option( 'timezone_string' );
		$offset         = empty( $fetched_offset ) ? 'UTC' : $fetched_offset;
		return $offset;
	}

}

if ( ! function_exists( 'zmeet_convert_to_minutes' ) ) {
	/**
	 * Convert hours and minutes to minutes.
	 *
	 * This function takes the given hour and minute values and converts them into minutes.
	 * It multiplies the hour value by 60 and adds the minute value to get the total minutes.
	 *
	 * @param int $hour The hour value to be converted.
	 * @param int $minute The minute value to be converted.
	 * @return int The total minutes calculated from the provided hour and minute values.
	 */
	function zmeet_convert_to_minutes( $hour, $minute ) {
		$hour   = $hour * 60;
		$result = $hour + $minute;
		return $result;
	}
}

if ( ! function_exists( 'zmeet_pro_plugin_exists' ) ) {
	/**
	 * Checks if the ZooMeet Pro plugin is installed.
	 *
	 * @return bool True if ZooMeet Pro plugin exists, false otherwise.
	 */
	function zmeet_pro_plugin_exists() {
		return file_exists( WP_PLUGIN_DIR . '/zoomeet-pro/zoomeet-pro.php' );
	}
}


if ( ! function_exists( 'zmeet_insert_meeting' ) ) {
	/**
	 * Inserts a new meeting post into the database.
	 *
	 * @param string $title              The title of the meeting.
	 * @param array  $meeting_settings   The settings for the meeting.
	 * @param string $meeting_description The description of the meeting.
	 *
	 * @return int|WP_Error The ID of the inserted meeting post on success, or a WP_Error object on failure.
	 */
	function zmeet_insert_meeting( $title, $meeting_settings, $meeting_description ) {
		$un_meeting_settings       = maybe_unserialize( $meeting_settings );
		$meeting_description_array = json_decode( $meeting_description, true );
		$meeting_description       = isset( $meeting_description_array['content'] ) ? wp_kses_post( $meeting_description_array['content'] ) : '';

		$new_meeting = array(
			'post_title'   => $title,
			'post_type'    => 'zmeet_meeting',
			'post_status'  => 'publish',
			'post_content' => '',
			'meta_input'   => array(
				'zmeet__meeting_settings' => $meeting_settings,
				'meeting_description'    => $meeting_description,
			),

		);

		$meeting_id = wp_insert_post( $new_meeting );

		$thumbnail_id = $un_meeting_settings['image_id'];

		// Set post thumbnail.
		if ( ! empty( $thumbnail_id ) ) {
			set_post_thumbnail( $meeting_id, $thumbnail_id );
		}

		if ( is_wp_error( $meeting_id ) ) {
			$meeting_id->add_data( array( 'status' => 400 ) );
			return $meeting_id;
		}

		return $meeting_id;
	}

}

if ( ! function_exists( 'zmeet_update_meeting' ) ) {
	/**
	 * Updates an existing meeting post in the database.
	 *
	 * @param string $title              The new title of the meeting.
	 * @param array  $meeting_settings   The new settings for the meeting.
	 * @param int    $meeting_id         The ID of the meeting post to update.
	 * @param string $meeting_description The new description of the meeting.
	 *
	 * @return int|WP_Error The number of affected rows on success, or a WP_Error object on failure.
	 */
	function zmeet_update_meeting( $title, $meeting_settings, $meeting_id, $meeting_description ) {
		$un_meeting_settings       = maybe_unserialize( $meeting_settings );
		$meeting_description_array = json_decode( $meeting_description, true );
		$meeting_description       = isset( $meeting_description_array['content'] ) ? wp_kses_post( $meeting_description_array['content'] ) : '';

		$arg = array(
			'ID'           => $meeting_id,
			'post_title'   => $title,
			'post_type'    => 'zmeet_meeting',
			'post_status'  => 'publish',
			'post_content' => '',
			'meta_input'   => array(
				'zmeet__meeting_settings' => $meeting_settings,
				'meeting_description'    => $meeting_description,
			),
		);

		$updated = wp_update_post( $arg );

		$thumbnail_id = isset( $un_meeting_settings['image_id'] ) ? $un_meeting_settings['image_id'] : '';

		// Check if the image ID is empty and remove the thumbnail if it is.
		if ( empty( $thumbnail_id ) ) {
			delete_post_thumbnail( $meeting_id );
		} else {
			// Set the post thumbnail if the image ID is not empty.
			set_post_thumbnail( $meeting_id, $thumbnail_id );
		}

		if ( ! $updated ) {
			return new WP_Error(
				'rest_not_updated',
				__( 'Sorry, the address could not be updated.', 'zoomeet' ),
				array( 'status' => 400 )
			);
		}
	}
}



if ( ! function_exists( 'zmeet_get_gmt_offset' ) ) {
	/**
	 * Get the GMT offset and its value for a given timezone.
	 *
	 * @param string $timezone The timezone identifier, e.g., 'Asia/Dhaka'.
	 *
	 * @return array An array containing the GMT offset string and its value.
	 */
	function zmeet_get_gmt_offset( $timezone ) {
		$dtz               = new DateTimeZone( $timezone );
		$offset_in_seconds = $dtz->getOffset( new DateTime() );
		$hours             = floor( abs( $offset_in_seconds ) / 3600 );
		$minutes           = floor( ( abs( $offset_in_seconds ) % 3600 ) / 60 );
		$gmt_offset        = ( $offset_in_seconds < 0 ? '-' : '+' ) . sprintf( '%02d:%02d', $hours, $minutes );

		list( $hours, $minutes ) = explode( ':', $gmt_offset );
		$gmt_offset_val          = ( $hours * 3600 ) + ( $minutes * 60 );

		return array(
			'gmt_offset'     => $gmt_offset,
			'gmt_offset_val' => $gmt_offset_val,
		);
	}
}


if ( ! function_exists( 'zmeet_get_timezone_abbr' ) ) {
	/**
	 * Get the timezone abbreviation (e.g. EDT, EST, PDT) for a datetime in a given timezone.
	 *
	 * Falls back to a GMT offset label (e.g. GMT+06:00) for timezones that have
	 * no abbreviation. The abbreviation is DST-aware, computed at the given moment.
	 *
	 * @param string $datetime_string The datetime string, e.g. '2026-07-07T10:00:00Z'.
	 * @param string $timezone        The timezone identifier, e.g. 'America/New_York'.
	 *
	 * @return string The abbreviation, or an empty string on failure.
	 */
	function zmeet_get_timezone_abbr( $datetime_string, $timezone ) {
		try {
			$datetime = new DateTime( $datetime_string );
			$datetime->setTimezone( new DateTimeZone( trim( $timezone ) ) );
			$abbr = $datetime->format( 'T' );

			// PHP returns offsets like '+06' for zones without an abbreviation.
			if ( '' !== $abbr && '+' !== $abbr[0] && '-' !== $abbr[0] ) {
				return $abbr;
			}

			return 'GMT' . $datetime->format( 'P' );
		} catch ( Exception $e ) {
			return '';
		}
	}
}


if ( ! function_exists( 'zoomeet_store_zoom_users' ) ) {
	/**
	 * Fetches and stores Zoom users using the provided Zoom API class instance.
	 *
	 * @param object $zoom_api Zoom API class instance with a `list_users` method.
	 *
	 * @return void
	 */
	function zoomeet_store_zoom_users( $zoom_api ) {
		$page      = 1;
		$user_data = $zoom_api->list_users( $page );

		if ( is_wp_error( $user_data ) ) {
			update_option( 'zmeet_zoom_users', array() );
			return;
		}

		$user_data = json_decode( $user_data, true );

		if ( ! empty( $user_data ) && isset( $user_data['users'] ) && is_array( $user_data['users'] ) && count( $user_data['users'] ) > 0 ) {
			$users_data = array();

			foreach ( $user_data['users'] as $user ) {
				$users_data[] = array(
					'id'           => $user['id'],
					'email'        => $user['email'],
					'display_name' => $user['display_name'],
				);
			}

			update_option( 'zmeet_zoom_users', $users_data );
		} else {
			update_option( 'zmeet_zoom_users', array() );
		}
	}
}

if ( ! function_exists( 'zmeet_format_meeting_datetime' ) ) {
	/**
	 * Format meeting datetime with translated day and month names.
	 *
	 * @param int    $timestamp The Unix timestamp to format.
	 * @param string $format    The format string (currently only supports 'l, F j, Y g:i A').
	 *
	 * @return string The formatted and translated datetime string.
	 */
	function zmeet_format_meeting_datetime( $timestamp, $format = 'l, F j, Y g:i A' ) {
		if ( empty( $timestamp ) ) {
			return '';
		}

		// Use WordPress wp_date() function for automatic localization.
		return wp_date( $format, $timestamp );
	}
}

if ( ! function_exists( 'zmeet_format_datetime_with_timezone' ) ) {
	/**
	 * Format datetime string with timezone conversion.
	 *
	 * @param string $datetime_string The datetime string to format.
	 * @param string $format The desired output format.
	 * @param string $timezone The target timezone.
	 *
	 * @return string Formatted datetime string.
	 */
	function zmeet_format_datetime_with_timezone( $datetime_string, $format, $timezone = 'UTC' ) {
		if ( empty( $datetime_string ) ) {
			return '';
		}

		try {
			$datetime = new DateTime( $datetime_string );

			if ( 'UTC' !== $timezone ) {
				$target_timezone = new DateTimeZone( $timezone );
				$datetime->setTimezone( $target_timezone );
			}

			return $datetime->format( $format );
		} catch ( Exception $e ) {
			return gmdate( $format, strtotime( $datetime_string ) );
		}
	}
}

if ( ! function_exists( 'zmeet_format_duration_display' ) ) {
	/**
	 * Format meeting duration for display with proper pluralization.
	 *
	 * @param int $duration_minutes Duration in minutes.
	 *
	 * @return string Formatted duration text.
	 */
	function zmeet_format_duration_display( $duration_minutes ) {
		if ( empty( $duration_minutes ) || $duration_minutes <= 0 ) {
			return '';
		}

		if ( $duration_minutes >= 60 ) {
			$hours   = floor( $duration_minutes / 60 );
			$minutes = $duration_minutes % 60;

			$hour_text = ( 1 === $hours ) ? __( 'hour', 'zoomeet' ) : __( 'hours', 'zoomeet' );
			$minute_text = ( 1 === $minutes ) ? __( 'minute', 'zoomeet' ) : __( 'minutes', 'zoomeet' );

			$duration_text = number_format_i18n( $hours ) . ' ' . $hour_text;

			if ( $minutes > 0 ) {
				$duration_text .= ' ' . number_format_i18n( $minutes ) . ' ' . $minute_text;
			}

			return $duration_text;
		} else {
			$minute_text = ( 1 === $duration_minutes ) ? __( 'minute', 'zoomeet' ) : __( 'minutes', 'zoomeet' );
			return number_format_i18n( $duration_minutes ) . ' ' . $minute_text;
		}
	}
}

if ( ! function_exists( 'zmeet_get_recurrence_description' ) ) {
	/**
	 * Generate human-readable recurrence description
	 *
	 * @param array $options Meeting options.
	 * @return string Human-readable recurrence description.
	 */
	function zmeet_get_recurrence_description( $options ) {
		if ( empty( $options['enable_recurring_meeting'] ) || ! $options['enable_recurring_meeting'] ) {
			return '';
		}

		$description = '';

		switch ( $options['recurrence_option'] ) {
			case '1': // Daily.
				$description = ( $options['repeat_day'] > 1 ) ?
					sprintf( __( 'Every %d days', 'zoomeet' ), $options['repeat_day'] ) :
					__( 'Daily', 'zoomeet' );
				break;

			case '2': // Weekly.
				$description = ( $options['repeat_weekly'] > 1 ) ?
					sprintf( __( 'Every %d weeks', 'zoomeet' ), $options['repeat_weekly'] ) :
					__( 'Weekly', 'zoomeet' );

				if ( ! empty( $options['weekdays'] ) && is_array( $options['weekdays'] ) ) {
					$day_names = array(
						1 => __( 'Sunday', 'zoomeet' ),
						2 => __( 'Monday', 'zoomeet' ),
						3 => __( 'Tuesday', 'zoomeet' ),
						4 => __( 'Wednesday', 'zoomeet' ),
						5 => __( 'Thursday', 'zoomeet' ),
						6 => __( 'Friday', 'zoomeet' ),
						7 => __( 'Saturday', 'zoomeet' ),
					);

					$days = array();
					$selected_days = is_string($options['weekdays']) ? explode(',', $options['weekdays']) : $options['weekdays'];
					foreach ( $selected_days as $weekday ) {
						if ( isset( $day_names[ $weekday ] ) ) {
							$days[] = $day_names[ $weekday ];
						}
					}

					if ( ! empty( $days ) ) {
						$description .= ' ' . __( 'on', 'zoomeet' ) . ' ' . implode( ', ', $days );
					}
				}
				break;

			case '3': // Monthly.
				$description = ( $options['repeat_monthly'] > 1 ) ?
					sprintf( __( 'Every %d months', 'zoomeet' ), $options['repeat_monthly'] ) :
					__( 'Monthly', 'zoomeet' );

				if ( isset( $options['occurs_on_monthly'] ) ) {
					if ( 'weekdays' === $options['occurs_on_monthly'] &&
						isset( $options['set_month_order'] ) &&
						isset( $options['set_monthly_weekday'] ) ) {

						$order_map = array(
							1  => __( 'first', 'zoomeet' ),
							2  => __( 'second', 'zoomeet' ),
							3  => __( 'third', 'zoomeet' ),
							4  => __( 'fourth', 'zoomeet' ),
							-1 => __( 'last', 'zoomeet' ),
						);

						$weekday_map = array(
							1 => __( 'Sunday', 'zoomeet' ),
							2 => __( 'Monday', 'zoomeet' ),
							3 => __( 'Tuesday', 'zoomeet' ),
							4 => __( 'Wednesday', 'zoomeet' ),
							5 => __( 'Thursday', 'zoomeet' ),
							6 => __( 'Friday', 'zoomeet' ),
							7 => __( 'Saturday', 'zoomeet' ),
						);

						$order   = $options['set_month_order'];
						$weekday = $options['set_monthly_weekday'];

						if ( isset( $order_map[ $order ] ) && isset( $weekday_map[ $weekday ] ) ) {
							$description .= ' ' . __( 'on the', 'zoomeet' ) . ' ' .
							$order_map[ $order ] . ' ' . $weekday_map[ $weekday ];
						}
					}
				}
				break;
		}

		if ( isset( $options['end_type'] ) ) {
			switch ( $options['end_type'] ) {
				case 'date':
					if ( isset( $options['end_date_time'] ) ) {
						$end_date = new DateTime( $options['end_date_time'] );
						$description .= ', ' . __( 'until', 'zoomeet' ) . ' ' .
						$end_date->format( get_option( 'date_format' ) );
					}
					break;

				case 'occurrences':
					if ( isset( $options['set_number_of_occurrences'] ) ) {
						$description .= ', ' . sprintf(
							_n( '%d time', '%d times', $options['set_number_of_occurrences'], 'zoomeet' ),
							$options['set_number_of_occurrences']
						);
					}
					break;
			}
		}

		return $description;
	}
}
