<?php

defined( 'ABSPATH' ) || exit;

use ThemeGrill\Zoom\Request;
use ThemeGrill\Zoom\ServerToServerAuth;
use Masteriyo\Addons\Zoom\Models\Setting;

/**
 * Zoom helper functions.
 *
 * @since 2.5.19
 *
 * @package Masteriyo\Addons\Zoom
 */

/**
 * Return true if the zoom credentials are set.
 * Doesn't validate credentials.
 *
 * @since 2.5.19
 *
 * @return boolean
 */
function masteriyo_is_zoom_credentials_set() {
	$setting = new Setting();

	$account_id    = $setting->get( 'account_id' );
	$client_id     = $setting->get( 'client_id' );
	$client_secret = $setting->get( 'client_secret' );

	return ! ( empty( $account_id ) || empty( $client_id ) || empty( $client_secret ) );
}

/**
 * Return true if the zoom credentials are valid for current user.
 *
 * @since 2.5.19
 *
 * @return true|\WP_Error
 */
function masteriyo_validate_zoom_credentials_for_current_user() {
	$setting       = new Setting();
	$account_id    = $setting->get( 'account_id' );
	$client_id     = $setting->get( 'client_id' );
	$client_secret = $setting->get( 'client_secret' );

	return masteriyo_validate_zoom_credentials( $account_id, $client_id, $client_secret );
}

/**
 * Return true if the zoom credentials are valid or else return message.
 *
 * @since 2.5.19
 *
 * @param string $account_id
 * @param string $client_id
 * @param string $client_secret
 *
 * @return true|\WP_Error
 */
function masteriyo_validate_zoom_credentials( $account_id, $client_id, $client_secret ) {
	$auth = new ServerToServerAuth( new Request() );

	$auth->set_credentials( $client_id, $client_secret, $account_id );

	$token = $auth->get_token();

	if ( isset( $token->error ) ) {
		if ( 'invalid_client' === $token->error ) {
			return new \WP_Error(
				'invalid_credentials',
				__( 'Invalid zoom credentials', 'learning-management-system' ),
				array( 'status' => 400 )
			);
		} else {
			return new \WP_Error(
				'zoom_cannot_save_credentials',
				$token->reason,
				array( 'status' => 400 )
			);
		}
	}

	return true;
}

/**
 * Get zoom.
 *
 * @since 2.6.5
 *
 * @param int|\Masteriyo\Addons\Zoom\Models\Zoom|\WP_Post $zoom Zoom id or Zoom Model or Post.
 *
 * @return \Masteriyo\Addons\Zoom\Models\Zoom|null
 */
function masteriyo_get_zoom( $zoom ) {
	$zoom_obj   = masteriyo( 'zoom' );
	$zoom_store = masteriyo( 'zoom.store' );

	if ( is_a( $zoom, \Masteriyo\Addons\Zoom\Models\Zoom::class ) ) {
		$id = $zoom->get_id();
	} elseif ( is_a( $zoom, \WP_Post::class ) ) {
		$id = $zoom->ID;
	} else {
		$id = $zoom;
	}

	try {
		$id = absint( $id );
		$zoom_obj->set_id( $id );
		$zoom_store->read( $zoom_obj );
	} catch ( \Exception $e ) {
		$zoom_obj = null;
	}

	/**
	 * Filters zoom object.
	 *
	 * @since 2.6.5
	 *
	 * @param \Masteriyo\Addons\Zoom\Models\Zoom $zoom_obj Zoom object.
	 * @param int|\Masteriyo\Addons\Zoom\Models\Zoom|WP_Post $zoom Zoom id or Zoom Model or Post.
	 */
	return apply_filters( 'masteriyo_get_zoom', $zoom_obj, $zoom );
}
