<?php // phpcs:ignore
/**
 * Mhub_Assets Class
 *
 * This class handles the loading of assets for the Meeting Hub plugin.
 *
 * @package SOVLIX\MHUB
 */

namespace SOVLIX\MHUB;

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

if ( ! class_exists( 'Mhub_Assets' ) ) {
	/**
	 * Mhub_Assets Class
	 *
	 * Manages the loading of assets, such as styles and scripts, for the Meeting Hub plugin.
	 *
	 * @since 1.0.0
	 */
	class Mhub_Assets {

		/**
		 * Mhub_Assets constructor.
		 *
		 * Initializes the Mhub_Assets class and sets up actions for enqueueing assets.
		 */
		public function __construct() {
			add_action( 'admin_enqueue_scripts', array( $this, 'mhub_admin_enqueue' ) );
			add_action( 'wp_enqueue_scripts', array( $this, 'mhub_frontend_enqueue' ), 9999 );
		}

		/**
		 * Meeting Hub enqueue for admin.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function mhub_admin_enqueue() {
			$create_meeting_url        = admin_url( 'admin.php?page=meetinghub-all-meetings#/meeting/create');
			$oauth_data                = get_option( 'mhub_zoom_global_oauth_data' );
			$mhub_google_account       = get_option( 'mhub_google_meet_account' );
			$server_auth_prepare       = mhub_is_server_auth_prepare();
			$mhub_jitsi_settings       = get_option( 'mhub_jitsi_settings' );
			$mhub_webex_settings       = get_option( 'mhub_webex_settings' );
			$mhub_zoom_settings        = get_option( 'mhub_zoom_settings');
			$mhub_google_meet_settings = get_option( 'mhub_google_meet_settings' );
			$mhub_msteams_settings     = get_option( 'mhub_msteams_settings' );
			$msteams_oauth_data        = get_option( 'mhub_msteams_global_oauth_data' );
			$current_user_id           = get_current_user_id();
			$webex_access_token        = get_user_meta( $current_user_id, 'mhub_webex_access_token', true );
			$jwt_token                 = get_transient( 'mhub_jitsi_jwt_token' );
			$mhub_is_pro_active        = false;

			if ( mhub_fs()->is_premium() ) {
				$mhub_is_pro_active = true;
			}

			$jitsi_active_status = '';

			if ( ! empty( $mhub_jitsi_settings ) ) {
				$domain_type = $mhub_jitsi_settings['domain_type'];

				if ( 'jitsi_random_public' === $domain_type ) {
					$jitsi_active_status = 'connected';
				} elseif ( 'jitsi_self_hosted' === $domain_type ) {
					$custom_domain = $mhub_jitsi_settings['custom_domain'];
					if ( ! empty( $custom_domain ) ) {
						$jitsi_active_status = 'connected';
					}
				} elseif ( 'jitsi_jass_premium' === $domain_type && ! empty( $jwt_token ) ) {
					$jitsi_active_status = 'connected';
				}
			}

			wp_enqueue_media();
			wp_enqueue_style( 'dashicons' );
			$screen = get_current_screen();

			wp_enqueue_style( 'mhub-admin-style', MHUB_ASSETS . '/css/admin.css', array(), MHUB_VERSION, 'all' );
			wp_enqueue_style( 'mhub-admin-fonts', MHUB_ASSETS . '/css/fonts.css', array(), MHUB_VERSION, 'all' );

			if ( $screen && ( strpos( $screen->id, 'meetinghub' ) !== false ) ) {

				wp_enqueue_script( 'mhub-admin-build', MHUB_ASSETS . '/dist/main.build.js', array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-i18n' ), MHUB_VERSION, true );
				wp_enqueue_script( 'mhub-admin-js', MHUB_ASSETS . '/js/admin.js', array( 'jquery' ), MHUB_VERSION, true );

				// Set script translations.
				wp_set_script_translations( 'mhub-admin-build', 'meetinghub', plugin_dir_path( MHUB_FILE ) . 'languages/' );

				// Localize the script and pass the create meeting URL.
				wp_localize_script(
					'mhub-admin-build',
					'mhubMeetingsData',
					array(
						'createMeetingUrl'          => $create_meeting_url,
						'oauthData'                 => ! empty( $oauth_data ) && mhub_is_server_auth_prepare() ? 'connected' : '',
						'zoom_sdk_auth'             => mhub_is_sdk_prepare() ? 'connected' : '',
						'webex_auth'                => ! empty( $webex_access_token ) && mhub_webex_auth_prepare() ? 'connected' : '',
						'google_account'            => $mhub_google_account,
						'jitsi_active_status'       => $jitsi_active_status,
						'mhub_jitsi_settings'       => $mhub_jitsi_settings,
						'mhub_webex_settings'       => $mhub_webex_settings,
						'mhub_zoom_settings'        => $mhub_zoom_settings,
						'mhub_google_meet_settings' => $mhub_google_meet_settings,
						'mhub_msteams_settings'     => $mhub_msteams_settings,
						'msteams_auth'              => ! empty( $msteams_oauth_data ) && mhub_msteams_auth_prepare() ? 'connected' : '',
						'mhub_timezone'             => mhub_timezone_offset(),
						'mhub_password'             => wp_generate_password( 8, false ),
						'zoom_users'                => get_option( 'mhub_zoom_users' ) ? get_option( 'mhub_zoom_users' ) : array(),
						'installed'                 => mhub_pro_plugin_exists(),
						'active'                    => $mhub_is_pro_active,
						'license'                   => $mhub_is_pro_active,
						'pricing_url'               => 'https://sovlix.com/meetinghub-pricing/',
						'google_meet_redirect_url'  => home_url( '/mhub-google-oauth/' ),
						'assets_path'               => MHUB_ASSETS,
						'checkout_url'              => mhub_fs()->get_upgrade_url(),
						'is_paying'                 => mhub_fs()->is_paying(),
						'ajax_url'                  => admin_url( 'admin-ajax.php' ),
						'nonce'                     => wp_create_nonce( 'mhub_admin_nonce' ),
						'siteurl'                   => get_site_url(),
						'admin_url'                 => admin_url( 'admin.php' ),
						'msteams_redirect_url'      => home_url( '/mhub-msteams-oauth/' ),
						'webex_redirect_url'        => home_url( '/mhub-webex-oauth/' ),
						'zoom_redirect_url'         => home_url( '/mhub-zoom-oauth/' ),
						'mce_btn_name'              => __( 'Meeting', 'meetinghub' ),
						'hide_floating_create_btn'  => false,
						'hide_floating_update_btn'  => false,
						'is_admin'                  => is_admin(),
						'strings'                   => Mhub_Translate::strings(),
						'noticeData'                => $this->get_admin_notices_data(),
						'dismissedNotices'          => get_option( 'mhub_dismissed_notices', array() ),
						'prepStatus'                => array(
							'zoom_oauth' => function_exists( 'mhub_is_server_auth_prepare' ) ? mhub_is_server_auth_prepare() : false,
							'zoom_sdk'   => function_exists( 'mhub_is_sdk_prepare' ) ? mhub_is_sdk_prepare() : false,
							'webex'      => function_exists( 'mhub_webex_auth_prepare' ) ? mhub_webex_auth_prepare() : false,
							'msteams'    => function_exists( 'mhub_msteams_auth_prepare' ) ? mhub_msteams_auth_prepare() : false,
							'google'     => function_exists( 'mhub_is_google_meet_prepare' ) ? mhub_is_google_meet_prepare() : false,
						),
						'total_meetings'            => (int) ( wp_count_posts( 'mhub_meeting' )->publish + ( isset( wp_count_posts( 'mhub_meeting' )->published ) ? wp_count_posts( 'mhub_meeting' )->published : 0 ) ),
						'upcoming_meetings'         => function_exists( 'mhub_count_upcoming_meetings' ) ? mhub_count_upcoming_meetings() : 0,
						'dashboard_stats'           => function_exists( 'mhub_get_dashboard_detailed_stats' ) ? mhub_get_dashboard_detailed_stats() : array(),
						'plugin_version'            => MHUB_VERSION,
						'docs_url'                  => 'https://meetinghub.sovlix.com/docs/',
						'community_url'             => 'https://www.facebook.com/groups/sovlixcommunity',
						'support_url'               => 'https://sovlix.com/support/',
						'tutorial_url'              => 'https://sovlix.com/meetinghub-tutorials/',
						'whats_new_url'             => 'https://sovlix.com/meetinghub-changelog/',
					)
				);

				wp_enqueue_style( 'mhub-admin-build-style', MHUB_ASSETS . '/dist/main.build.css', array(), MHUB_VERSION, 'all' );
			}
		}

		/**
		 * Get admin notices data for React.
		 *
		 * @return array
		 */
		private function get_admin_notices_data() {
			$notices           = array();
			$dismissed_notices = get_option( 'mhub_dismissed_notices', array() );
			$current_time      = time();

			$configs = array(
				'zoom_oauth' => array(
					'prepared'  => function_exists( 'mhub_is_server_auth_prepare' ) ? mhub_is_server_auth_prepare() : true,
					'connected' => function_exists( 'mhub_is_zoom_oauth_connected' ) ? mhub_is_zoom_oauth_connected() : true,
				),
				'zoom_sdk'   => array(
					'prepared' => function_exists( 'mhub_is_sdk_prepare' ) ? mhub_is_sdk_prepare() : true,
				),
				'webex'      => array(
					'prepared'  => function_exists( 'mhub_webex_auth_prepare' ) ? mhub_webex_auth_prepare() : true,
					'connected' => function_exists( 'mhub_is_webex_connected' ) ? mhub_is_webex_connected() : true,
				),
				'msteams'    => array(
					'prepared'  => function_exists( 'mhub_msteams_auth_prepare' ) ? mhub_msteams_auth_prepare() : true,
					'connected' => function_exists( 'mhub_is_msteams_connected' ) ? mhub_is_msteams_connected() : true,
				),
				'google'     => array(
					'prepared'  => function_exists( 'mhub_is_google_meet_prepare' ) ? mhub_is_google_meet_prepare() : true,
					'connected' => function_exists( 'mhub_is_google_meet_connected' ) ? mhub_is_google_meet_connected() : true,
				),
				'legacy_redirect' => array(
					'prepared'  => false,
					'connected' => false,
				),
			);

			// Logic to distinguish between new install and update for the legacy redirect notice
			$first_install_version = get_option( 'mhub_first_install_version' );
			$has_config            = get_option( 'mhub_zoom_global_oauth_data' ) || get_option( 'mhub_webex_settings' ) || get_option( 'mhub_google_meet_settings' );

			if ( ! $first_install_version ) {
				if ( ! $has_config ) {
					// Brand new user: mark their first version as this one
					$first_install_version = MHUB_VERSION;
					update_option( 'mhub_first_install_version', $first_install_version );
				} else {
					// Existing user: mark as older version so they see the notice
					$first_install_version = '1.24.0';
					update_option( 'mhub_first_install_version', $first_install_version );
				}
			}

			// If the user started with 1.25.0+, they don't need the legacy redirect notice
			if ( version_compare( $first_install_version, '1.25.0', '>=' ) ) {
				unset( $configs['legacy_redirect'] );
			}

			foreach ( $configs as $id => $status ) {
				// Check if dismissed
				if ( isset( $dismissed_notices[ $id ] ) ) {
					$expiry = $dismissed_notices[ $id ];
					if ( -1 === $expiry || $expiry > $current_time ) {
						continue; // Still dismissed
					}
				}

				if ( ! $status['prepared'] ) {
					$notice = array(
						'id'    => $id,
						'type'  => 'warning',
						'state' => 'unprepared',
					);

					if ( 'legacy_redirect' === $id ) {
						$notice['title']    = __( 'Action Required: Redirect URIs Updated', 'meetinghub' );
						$notice['message']  = __( 'If you face connection issues with Zoom, Webex, or Google Meet, please go to the platform\'s "Connect" tab, copy the new Redirect URL provided there, and set it again in your account settings (Zoom Marketplace, Google Console, or Webex Developer Portal).', 'meetinghub' );
						$notice['linkText'] = '';
						$notice['link']     = '';
					}

					$notices[] = $notice;
				} elseif ( isset( $status['connected'] ) && ! $status['connected'] ) {
					$notices[] = array(
						'id'    => $id,
						'type'  => 'info',
						'state' => 'unconnected',
					);
				}
			}

			return $notices;
		}

		/**
		 * Meeting Hub enqueue for frontend.
		 *
		 * @return void
		 *
		 * @since 1.0.0
		 */
		public function mhub_frontend_enqueue() {

			$oauth_data                = get_option( 'mhub_zoom_global_oauth_data' );
			$server_auth_prepare       = mhub_is_server_auth_prepare();
			$mhub_jitsi_settings       = get_option( 'mhub_jitsi_settings' );
			$mhub_webex_settings       = get_option( 'mhub_webex_settings' );
			$mhub_zoom_settings        = get_option( 'mhub_zoom_settings' );
			$mhub_google_meet_settings = get_option( 'mhub_google_meet_settings' );
			$current_user_id           = get_current_user_id();
			$webex_access_token        = get_user_meta( $current_user_id, 'mhub_webex_access_token', true );
			$jwt_token                 = get_transient( 'mhub_jitsi_jwt_token' );
			$mhub_google_account       = get_option( 'mhub_google_meet_account' );
			wp_enqueue_style( 'dashicons' );

			$mhub_is_pro_active = false;

			if ( mhub_fs()->is_premium() ) {
				$mhub_is_pro_active = true;
			}

			$jitsi_active_status = '';

			if ( ! empty( $mhub_jitsi_settings ) ) {
				$domain_type = $mhub_jitsi_settings['domain_type'];
				if ( 'jitsi_random_public' === $domain_type ) {
					$jitsi_active_status = 'connected';
				} elseif ( 'jitsi_self_hosted' === $domain_type ) {
					$custom_domain = $mhub_jitsi_settings['custom_domain'];
					if ( ! empty( $custom_domain ) ) {
						$jitsi_active_status = 'connected';
					}
				} elseif ( 'jitsi_jass_premium' === $domain_type && ! empty( $jwt_token ) ) {
					$jitsi_active_status = 'connected';
				}
			}

			if ( is_user_logged_in() ) {

				wp_enqueue_script( 'mhub-frontend-main-build', MHUB_ASSETS . '/dist/main.build.js', array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-i18n' ), MHUB_VERSION, true );

				wp_enqueue_media();
				wp_enqueue_style( 'dashicons' );

				wp_localize_script(
					'mhub-frontend-main-build',
					'mhubMeetingsData',
					array(
						'oauthData'                 => ! empty( $oauth_data ) && $server_auth_prepare ? 'connected' : '',
						'webex_auth'                => ! empty( $webex_access_token ) ? 'connected' : '',
						'jitsi_active_status'       => $jitsi_active_status,
						'mhub_jitsi_settings'       => $mhub_jitsi_settings,
						'mhub_webex_settings'       => $mhub_webex_settings,
						'google_account'            => $mhub_google_account,
						'mhub_zoom_settings'        => $mhub_zoom_settings,
						'mhub_google_meet_settings' => $mhub_google_meet_settings,
						'mhub_timezone'             => mhub_timezone_offset(),
						'mhub_password'             => wp_generate_password( 8, false ),
						'zoom_users'                => get_option( 'mhub_zoom_users' ),
						'installed'                 => mhub_pro_plugin_exists(),
						'active'                    => $mhub_is_pro_active,
						'license'                   => $mhub_is_pro_active,
						'checkout_url'              => 'https://sovlix.com/meetinghub-pricing/',
						'siteurl'                   => get_site_url(),
						'hide_floating_create_btn'  => true,
						'hide_floating_update_btn'  => true,
						'mce_btn_name'              => __( 'Meeting', 'meetinghub' ),
						'is_admin'                  => current_user_can( 'manage_options' ),
						'ajax_url'                  => admin_url( 'admin-ajax.php' ),
						'nonce'                     => wp_create_nonce( 'mhub_admin_nonce' ),
						'strings'                   => Mhub_Translate::strings(),
					)
				);
			}

			wp_enqueue_style( 'mhub-admin-fonts', MHUB_ASSETS . '/css/fonts.css', array(), MHUB_VERSION, 'all' );


			wp_enqueue_script( 'mhub-external-api-js', MHUB_ASSETS . '/js/external_api.js', array(), MHUB_VERSION, true );
			if ( ! $mhub_is_pro_active ) {
				wp_enqueue_script( 'mhub-jitsi-meet-js', MHUB_ASSETS . '/js/jitsi-meet.js', array( 'jquery' ), MHUB_VERSION, true );

				$mhub_jitsi_settings_serialized = get_option( 'mhub_jitsi_settings' );
				$mhub_jitsi_settings            = maybe_unserialize( $mhub_jitsi_settings_serialized );
				$jwt_token                      = get_transient( 'mhub_jitsi_jwt_token' );

				// Localize the script and pass the create meeting URL.
				wp_localize_script(
					'mhub-jitsi-meet-js',
					'mhub_frontend',
					array(
						'mhub_jitsi_settings' => $mhub_jitsi_settings,
						'jwt'                 => $jwt_token,
					)
				);
			}

			wp_enqueue_script( 'mhub-frontend-js', MHUB_ASSETS . '/js/frontend.js', array( 'jquery', 'moment' ), MHUB_VERSION, true );

			wp_enqueue_script( 'mhub-frontend-build', MHUB_ASSETS . '/dist/frontend.build.js', array( 'wp-blocks', 'wp-element', 'wp-i18n' ), MHUB_VERSION, true );

			wp_enqueue_style( 'mhub-frontend-build-style', MHUB_ASSETS . '/dist/main.build.css', array(), MHUB_VERSION, 'all' );

			// Localize script to pass data to JavaScript.
			wp_localize_script(
				'mhub-frontend-build',
				'mhub_frontend_data',
				array(
					'ajax_url'        => admin_url( 'admin-ajax.php' ),
					'nonce'           => wp_create_nonce( 'mhub_frontend_nonce' ),
					'strings'         => Mhub_Translate::strings(),
					'is_admin'        => current_user_can( 'manage_options' ),
					'page_id'         => get_the_ID(),
					'visibility_mode' => get_post_meta( get_the_ID(), '_mhub_visibility_mode', true ) ? get_post_meta( get_the_ID(), '_mhub_visibility_mode', true ) : 'user',
					'selected_roles'  => get_post_meta( get_the_ID(), '_mhub_visibility_roles', true ) ? get_post_meta( get_the_ID(), '_mhub_visibility_roles', true ) : array(),
					'selected_users'  => get_post_meta( get_the_ID(), '_mhub_visibility_users', true ) ? get_post_meta( get_the_ID(), '_mhub_visibility_users', true ) : array(),
				)
			);

			wp_localize_script(
				'mhub-frontend-js',
				'mhub_frontend_params',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'mhub_frontend_nonce' ),
				)
			);

			wp_enqueue_script( 'mhub-countdown-js', MHUB_ASSETS . '/js/countdown.js', array( 'jquery', 'moment' ), MHUB_VERSION, true );

			wp_localize_script(
				'mhub-countdown-js',
				'mhubtran',
				array(
					'strings' => Mhub_Translate::strings(),
				)
			);
			wp_enqueue_style( 'mhub-meeting-css', MHUB_ASSETS . '/css/meeting-style.css', array(), MHUB_VERSION, 'all' );
		}
	}
}
