<?php //phpcs:ignore

/**
 * File: Mhub_Ajax.php
 *
 * The Mhub_Ajax class handles AJAX requests and provides functionalities for generating referral coupons.
 *
 * @package ECRE
 * @since   1.0.0
 */

namespace SOVLIX\MHUB;

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

if ( ! class_exists( 'Mhub_Ajax' ) ) {
	/**
	 * The Mhub_Ajax class handles AJAX requests and provides functionalities for generating referral coupons.
	 *
	 * @since 1.0.0
	 */
	class Mhub_Ajax {
		/**
		 * Mhub_Ajax constructor.
		 *
		 * Initializes the class and sets up AJAX request handlers.
		 */
		public function __construct() {
			add_action( 'wp_ajax_mhub_meeting_action', array( $this, 'handle_mhub_meeting_action' ) );
			add_action( 'wp_ajax_mhub_meeting_list', array( $this, 'mhub_meeting_lists' ) );
			add_action( 'wp_ajax_nopriv_mhub_meeting_list', array( $this, 'mhub_meeting_lists' ) );
			add_action( 'wp_ajax_mhub_google_meeting_list', array( $this, 'mhub_google_meeting_lists' ) );
			add_action( 'wp_ajax_nopriv_mhub_google_meeting_list', array( $this, 'mhub_google_meeting_lists' ) );
			add_action( 'wp_ajax_mhub_reset_google_meet_credential', array( $this, 'reset_credential' ) );
			add_action( 'wp_ajax_mhub_check_google_meet_credential', array( $this, 'check_credential_exists' ) );
			add_action( 'wp_ajax_mhub_check_google_meet_permission', array( $this, 'mhub_check_google_meet_permission' ) );
			add_action( 'wp_ajax_mhub_get_link', array( $this, 'mhub_get_link' ) );
			add_action( 'wp_ajax_mhub_renew_zoom_oauth', array( $this, 'mhub_renew_zoom_oauth_callback' ) );
			add_action( 'wp_ajax_mhub_save_visibility_mode', array( $this, 'mhub_save_visibility_mode' ) );
			add_action( 'wp_ajax_mhub_fetch_users', array( $this, 'mhub_fetch_users_callback' ) );
			add_action( 'wp_ajax_mhub_fetch_roles', array( $this, 'mhub_fetch_roles_callback' ) );
			add_action( 'wp_ajax_mhub_fetch_users_by_ids', array( $this, 'mhub_fetch_users_by_ids' ) );
			add_action( 'wp_ajax_nopriv_mhub_fetch_users_by_ids', array( $this, 'mhub_fetch_users_by_ids' ) );
			add_action( 'wp_ajax_mhub_dismiss_notice', array( $this, 'mhub_dismiss_notice' ) );
		}

		/**
		 * Dismiss an admin notice.
		 */
		public function mhub_dismiss_notice() {
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mhub_admin_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );
			}

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ), 403 );
			}

			$notice_id = isset( $_POST['notice_id'] ) ? sanitize_text_field( wp_unslash( $_POST['notice_id'] ) ) : '';
			$duration  = isset( $_POST['duration'] ) ? sanitize_text_field( wp_unslash( $_POST['duration'] ) ) : '';

			if ( empty( $notice_id ) || empty( $duration ) ) {
				wp_send_json_error( array( 'message' => 'Missing data.' ), 400 );
			}

			$dismissed_notices = get_option( 'mhub_dismissed_notices', array() );
			$expiry            = -1; // Default to forever

			if ( 'forever' !== $duration ) {
				$days   = (int) $duration;
				$expiry = time() + ( $days * DAY_IN_SECONDS );
			}

			$dismissed_notices[ $notice_id ] = $expiry;

			update_option( 'mhub_dismissed_notices', $dismissed_notices );

			wp_send_json_success( array( 'message' => 'Notice dismissed successfully.' ) );
		}

		/**
		 * Fetch users by IDs via AJAX.
		 *
		 * @return void
		 */
		public function mhub_fetch_users_by_ids() {
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );
			}

			// Must be logged in.
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Not logged in' ), 401 );
			}

			// Check user capability.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ) );
			}

			$user_ids = isset( $_POST['user_ids'] ) ? array_map( 'absint', wp_unslash( (array) $_POST['user_ids'] ) ) : array();

			if ( empty( $user_ids ) ) {
				wp_send_json_success( array() );
			}

			$users = get_users(
				array(
					'include' => $user_ids,
					'fields'  => array( 'ID', 'display_name', 'user_email' ),
				)
			);

			$options = array_map(
				function ( $user ) {
					return array(
						'value' => (string) $user->ID,
						'label' => esc_html( $user->display_name ) . ' (' . esc_html( $user->user_email ) . ')',
					);
				},
				$users
			);

			wp_send_json_success( $options );
		}

		/**
		 * AJAX callback to fetch all available WordPress user roles.
		 *
		 * This function is triggered via an authenticated AJAX request from the frontend.
		 * It verifies the nonce for security, retrieves all registered user roles,
		 * and returns them in a structured JSON response suitable for use in
		 * dropdowns or selectors.
		 *
		 * @since 1.0.0
		 *
		 * @return void Outputs a JSON success response with the list of roles.
		 */
		public function mhub_fetch_roles_callback() {
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );
			}

			// Must be logged in.
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Not logged in' ), 401 );
			}

			// Check user capability.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ) );
			}

			$roles = wp_roles()->get_names();

			$role_options = array();

			foreach ( $roles as $key => $label ) {
				$role_options[] = array(
					'value' => $key,
					'label' => $label,
				);
			}

			wp_send_json_success( $role_options );
		}

		/**
		 * Alternative simpler approach - optimized version of existing method
		 * Replace your existing mhub_fetch_users_callback with this
		 */
		public function mhub_fetch_users_callback() {
			// Nonce check.
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );
			}

			// Must be logged in.
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Not logged in' ), 401 );
			}

			// Check user capability.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ) );
			}

			global $wpdb;

			// Sanitize and validate search input.
			$search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';

			// Require minimum 3 characters to avoid extremely heavy queries on large datasets.
			if ( strlen( $search ) < 3 ) {
				wp_send_json_success( array() );
				return;
			}

			// Create cache key for this search.
			$cache_key = 'mhub_user_search_' . md5( $search );

			// Try to get cached results first.
			$cached_results = wp_cache_get( $cache_key, 'mhub_users' );
			if ( false !== $cached_results ) {
				wp_send_json_success( $cached_results );
				return;
			}

			// Prepare search term for LIKE query.
			$search_term = '%' . $wpdb->esc_like( $search ) . '%';

			// Execute prepared statement directly without intermediate variable.
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$results = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT ID, display_name, user_login, user_email
					FROM {$wpdb->users}
					WHERE display_name LIKE %s 
						OR user_login LIKE %s 
						OR user_email LIKE %s
					ORDER BY display_name ASC",
					$search_term,
					$search_term,
					$search_term
				)
			);
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

			// Handle empty results.
			if ( ! $results ) {
				// Cache empty results for 5 minutes to avoid repeated queries.
				wp_cache_set( $cache_key, array(), 'mhub_users', 300 );
				wp_send_json_success( array() );
				return;
			}

			// Transform results using array_map for better performance.
			$data = array_map(
				function ( $user ) {
					return array(
						'value' => (string) $user->ID,
						'label' => sprintf(
							'%s (%s - %s)',
							esc_html( $user->display_name ),
							esc_html( $user->user_login ),
							esc_html( $user->user_email )
						),
					);
				},
				$results
			);

			// Cache results for 15 minutes.
			wp_cache_set( $cache_key, $data, 'mhub_users', 900 );

			// Return successful response.
			wp_send_json_success( $data );
		}

		/**
		 * AJAX callback to save visibility mode settings for a page.
		 *
		 * @since 1.0.0
		 *
		 * @return void Outputs JSON response and exits.
		 */
		public function mhub_save_visibility_mode() {
			// Verify nonce for security.
			if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );
			}

			// Must be logged in.
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Not logged in' ), 401 );
			}

			// Check user capability.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ) );
			}

			// Sanitize and validate input data.
			$page_id = isset( $_POST['page_id'] ) ? absint( $_POST['page_id'] ) : 0;
			$mode    = isset( $_POST['mode'] ) ? sanitize_text_field( wp_unslash( $_POST['mode'] ) ) : 'user';

			// Validate page ID.
			if ( 0 === $page_id ) {
				wp_send_json_error( __( 'Invalid page ID.', 'meetinghub' ) );
				return;
			}

			// Handle roles data.
			$roles = array();
			if ( isset( $_POST['roles'] ) ) {
				$roles_input = sanitize_text_field( wp_unslash( $_POST['roles'] ) );
				$roles_raw   = json_decode( stripslashes( $roles_input ), true );
				if ( is_array( $roles_raw ) ) {
					$roles = array_map( 'sanitize_text_field', $roles_raw );
				}
			}

			// Handle users data.
			$users = array();
			if ( isset( $_POST['users'] ) ) {
				$users_input = sanitize_text_field( wp_unslash( $_POST['users'] ) );
				$users_raw   = json_decode( stripslashes( $users_input ), true );
				if ( is_array( $users_raw ) ) {
					$users = array_map( 'absint', $users_raw );
				}
			}

			// Save the visibility settings.
			update_post_meta( $page_id, '_mhub_visibility_mode', $mode );
			update_post_meta( $page_id, '_mhub_visibility_roles', $roles );
			update_post_meta( $page_id, '_mhub_visibility_users', $users );

			wp_send_json_success( __( 'Visibility settings saved successfully.', 'meetinghub' ) );
		}


		/**
		 * Handles AJAX requests for fetching meeting lists.
		 *
		 * This function verifies the nonce for security, fetches the list of meetings,
		 * and returns the meetings as a JSON response. It is intended to be used as a
		 * callback for AJAX requests in WordPress.
		 *
		 * @since 1.13.1
		 *
		 * @return void Outputs JSON response and exits.
		 */
		public function mhub_meeting_lists() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( __( 'Invalid security token.', 'meetinghub' ) );
				return;
			}

			// Sanitize and validate input data.
			$page_id = isset( $_POST['page_id'] ) ? absint( $_POST['page_id'] ) : 0;
			$mode    = isset( $_POST['visibility_mode'] ) ? sanitize_text_field( wp_unslash( $_POST['visibility_mode'] ) ) : 'user';

			// Handle roles data - ignore PHPCS warning as we sanitize after JSON decode.
			$roles = array();
			if ( isset( $_POST['roles'] ) ) {
				$roles_input = isset( $_POST['roles'] ) ? sanitize_text_field( wp_unslash( $_POST['roles'] ) ) : '';
				$roles_raw   = json_decode( stripslashes( $roles_input ), true );
				if ( is_array( $roles_raw ) ) {
					$roles = array_map( 'sanitize_text_field', $roles_raw );
				}
			}

			// Handle users data - ignore PHPCS warning as we sanitize after JSON decode.
			$users = array();
			if ( isset( $_POST['users'] ) ) {
				$users_input = isset( $_POST['users'] ) ? sanitize_text_field( wp_unslash( $_POST['users'] ) ) : '';
				$users_raw   = json_decode( stripslashes( $users_input ), true );
				if ( is_array( $users_raw ) ) {
					$users = array_map( 'absint', $users_raw );
				}
			}

			// Check if we should use passed values or saved values.
			$use_passed_values = isset( $_POST['use_passed_values'] ) && '1' === $_POST['use_passed_values'];

			// Fetch meetings based on the specified mode and parameters.
			$meetings = mhub_meetings_by_mode( $mode, $page_id, $roles, $users, $use_passed_values );

			// Handle potential errors from the helper function.
			if ( is_wp_error( $meetings ) ) {
				wp_send_json_error( $meetings->get_error_message() );
				return;
			}

			wp_send_json_success( $meetings );
		}


		/**
		 * Handles AJAX requests to fetch a list of Google Meet meetings.
		 *
		 * This function verifies the nonce for security, interacts with the Google Meet API
		 * through the `Mhub_Events` class, and returns the list of meetings in JSON format.
		 *
		 * @return void
		 *
		 * @throws WP_Error If the nonce verification fails.
		 */
		public function mhub_google_meeting_lists() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'mhub_admin_nonce' ) ) {
				wp_send_json_error( 'Invalid nonce.' );
			}

			$google_api = new \SOVLIX\MHUB\Googlemeet\Mhub_Events();

			$google_meet_response = $google_api->get_all_meetings();

			wp_send_json_success( $google_meet_response );
		}

		/**
		 * Handle end meeting action
		 */
		public function handle_mhub_meeting_action() {
			// Verify nonce for security.
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'mhub_frontend_nonce' ) ) {
				wp_send_json_error( 'Invalid nonce.' );
			}

			// Must be logged in.
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Not logged in' ), 401 );
			}

			// Check user capability.
			if ( ! current_user_can( 'edit_posts' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ), 403 );
			}

			$response = '';

			// Retrieve and sanitize posted data.
			$meeting_id     = isset( $_POST['meeting_id'] ) ? sanitize_text_field( wp_unslash( $_POST['meeting_id'] ) ) : '';
			$post_id        = isset( $_POST['post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['post_id'] ) ) : '';
			$meeting_status = isset( $_POST['meeting_status'] ) ? sanitize_text_field( wp_unslash( $_POST['meeting_status'] ) ) : '';

			if ( 'end' === $meeting_status ) {
				update_post_meta( $post_id, 'mhub_meeting_status', 'end' );
				$response = 'Meeting ended successfully.';
			}

			if ( 'resume' === $meeting_status ) {
				update_post_meta( $post_id, 'mhub_meeting_status', 'resume' );
				$response = 'Meeting resumed successfully.';
			}

			if ( 'start' === $meeting_status ) {
				update_post_meta( $post_id, 'mhub_meeting_start_status', 'start' );
				$response = 'Meeting started successfully.';
			}

			if ( 'stop' === $meeting_status ) {
				update_post_meta( $post_id, 'mhub_meeting_start_status', 'stop' );
				$response = 'Meeting stoped successfully.';
			}

			// Example: Respond with a success message.
			wp_send_json_success( $response );
		}

		/**
		 * Reset user credentials and tokens by deleting the associated files.
		 *
		 * Deletes the `credential.json` and `token.json` files for the current user.
		 * Sends a JSON response with the operation result.
		 *
		 * @return void
		 */
		public function reset_credential() {

			if ( defined( 'DOING_AJAX' ) && ! DOING_AJAX ) {
				wp_send_json_error( __( 'Invalid request', 'meetinghub' ), 400 );
			}

			// 1) Nonce check: prevents CSRF / forgery
			$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'mhub_admin_nonce' ) ) {
				wp_send_json_error( __( 'Nonce verification failed', 'meetinghub' ), 403 );
			}

			// 2) Capability check: only admins (or roles with manage_options) can run this
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( esc_html__( 'You are not authorized to perform this operation', 'meetinghub' ), 403 );
			}

			// Generate file names based on the current user's login name.
			$credential_file_name = 'credential.json';
			$token_file_name      = 'token.json';

			// File paths.
			$upload_dir           = \trailingslashit( wp_upload_dir()['basedir'] ) . 'mhub-json/';
			$credential_file_path = $upload_dir . $credential_file_name;
			$token_file_path      = $upload_dir . $token_file_name;

			// Initialize response messages.
			$messages = array();

			// Attempt to delete the credential file.
			if ( file_exists( $credential_file_path ) ) {
				if ( unlink( $credential_file_path ) ) {
					$messages[] = __( 'Credential file reset successfully!', 'meetinghub' );
				} else {
					$messages[] = __( 'Failed to reset credential file.', 'meetinghub' );
				}
			} else {
				$messages[] = __( 'Credential file does not exist.', 'meetinghub' );
			}

			// Attempt to delete the token file.
			if ( file_exists( $token_file_path ) ) {
				if ( unlink( $token_file_path ) ) {
					$messages[] = __( 'Token file reset successfully!', 'meetinghub' );
				} else {
					$messages[] = __( 'Failed to reset token file.', 'meetinghub' );
				}
			} else {
				$messages[] = __( 'Token file does not exist.', 'meetinghub' );
			}

			// Check if any success messages exist.
			if ( array_filter( $messages, fn( $msg ) => str_contains( $msg, 'successfully' ) ) ) {
				wp_send_json_success( implode( ' ', $messages ) );
			} else {
				wp_send_json_error( implode( ' ', $messages ) );
			}
		}

		/**
		 * Check if the user's credential file exists.
		 *
		 * Verifies the existence of the `credential.json` file for the current user.
		 * Sends a JSON response with the result.
		 *
		 * @return void
		 */
		public function check_credential_exists() {
			$file_path = trailingslashit( wp_upload_dir()['basedir'] ) . 'mhub-json/credential.json';

			if ( file_exists( $file_path ) ) {
				wp_send_json_success( array( 'message' => 'Credential exists' ) );
			} else {
				wp_send_json_error( array( 'message' => 'Credential not found' ) );
			}

			wp_die();
		}

		/**
		 * Retrieve the Google Meet consent screen URL.
		 *
		 * Uses the `Mhub_Meet` instance to generate and return the consent screen URL.
		 * Sends a JSON response with the URL or an error message.
		 *
		 * @return void
		 */
		public function mhub_get_link() {
			$google_meet = Googlemeet\Mhub_Meet::get_instance();
			$link        = $google_meet->get_consent_screen_url();

			if ( ! empty( $link ) ) {
				wp_send_json_success( array( 'link' => $link ) );
			} else {
				wp_send_json_error( __( 'Failed to retrieve the consent screen URL.', 'meetinghub' ) );
			}
		}

		/**
		 * Check Google Meet permissions and update the plugin settings.
		 *
		 * Verifies if the Google Meet application is permitted.
		 * Updates the `mhub_google_meet_account` option based on the permission status.
		 * Sends a JSON response with the permission status or an error message.
		 *
		 * @return void
		 */
		public function mhub_check_google_meet_permission() {
			// Check if the user has sufficient permissions (optional but recommended).
			if ( ! is_user_logged_in() ) {
				wp_send_json_error( array( 'message' => 'Unauthorized access' ), 403 );
				return;
			}

			// Initialize Google Meet instance.
			try {
				$google_meet = Googlemeet\Mhub_Meet::get_instance();
				$permission  = $google_meet->is_app_permitted();

				if ( $permission ) {
					update_option( 'mhub_google_meet_account', 'connected' );
				} else {
					update_option( 'mhub_google_meet_account', '' );
				}

				// Send success response with permission status.
				wp_send_json_success( array( 'permission' => $permission ) );
			} catch ( Exception $e ) {
				// Handle any exceptions and send an error response.
				update_option( 'mhub_google_meet_account', '' );
				wp_send_json_error( array( 'message' => $e->getMessage() ), 500 );
			}
		}

		/**
		 * Handles the renewal of Zoom OAuth tokens via AJAX.
		 *
		 * This function verifies the request, checks user permissions, retrieves
		 * the stored Zoom OAuth credentials, and attempts to renew the access token.
		 * If successful, it saves the new token; otherwise, it returns an error response.
		 *
		 * @since 1.0.0
		 * @return void Outputs a JSON response indicating success or failure.
		 */
		public function mhub_renew_zoom_oauth_callback() {
			// Verify nonce.
			$nonce = isset( $_POST['security'] ) ? sanitize_text_field( wp_unslash( $_POST['security'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'mhub_admin_nonce' ) ) {
				wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
			}

			// Check user capability.
			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized request.' ) );
			}

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

			// Validate settings.
			if ( ! is_array( $zoom_settings ) || empty( $zoom_settings ) ) {
				update_option( 'mhub_zoom_global_oauth_data', '' );
				wp_send_json_error( array( 'message' => 'Renew failed. Set OAuth credentials first.' ) );
			}

			// Extract credentials.
			$account_id    = $zoom_settings['oauth_account_id'] ?? '';
			$client_id     = $zoom_settings['oauth_client_id'] ?? '';
			$client_secret = $zoom_settings['oauth_client_secret'] ?? '';

			// Ensure all required fields are set.
			if ( empty( $account_id ) || empty( $client_id ) || empty( $client_secret ) ) {
				update_option( 'mhub_zoom_global_oauth_data', '' );
				wp_send_json_error( array( 'message' => 'Renew failed. Missing OAuth credentials.' ) );
			}

			// Attempt to renew the access token.
			$zoom_auth = \SOVLIX\MHUB\Zoom\Mhub_S2SO_Auth::get_instance();
			$result    = $zoom_auth->generate_and_save_access_token( $account_id, $client_id, $client_secret );

			if ( is_wp_error( $result ) ) {
				update_option( 'mhub_zoom_global_oauth_data', '' );
				wp_send_json_error( array( 'message' => 'OAuth renewal failed: ' . $result->get_error_message() ) );
			}

			// Respond with success.
			wp_send_json_success( array( 'message' => 'OAuth Token Renewed Successfully' ) );
		}
	}
}
