<?php
/**
 * Wemeet Configuration Manager
 *
 * Manages plugin configuration, Webex credentials validation, and plugin action links.
 *
 * @package SOVLIX\WEMEET\Admin
 */

namespace SOVLIX\WEMEET\Admin;

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

/**
 * Wemeet_Config_Manager Class
 *
 * Handles plugin configuration and Webex credentials management.
 *
 * @since 1.0.0
 */
class Wemeet_Config_Manager {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_filter( 'plugin_action_links', array( $this, 'add_settings_link' ), 11, 2 );
		// Clear access token if Webex auth is not prepared.
		self::clear_token_if_not_prepared();
	}

	/**
	 * Adds a "Settings" link to the plugin actions on the WordPress Plugins page.
	 *
	 * @param array  $actions     The existing array of action links for the plugin.
	 * @param string $plugin_file The file path of the plugin being processed.
	 *
	 * @return array The modified array of action links.
	 *
	 * @since 1.0.0
	 */
	public function add_settings_link( $actions, $plugin_file ) {
		if ( 'wemeet/wemeet.php' === $plugin_file ) {
			$settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=wemeet-settings' ) ) . '">' . esc_html__( 'Settings', 'wemeet' ) . '</a>';
			if ( ! in_array( $settings_link, $actions, true ) ) {
				array_unshift( $actions, $settings_link );
			}
		}

		return $actions;
	}

	/**
	 * Check if Webex authentication is prepared.
	 *
	 * This function retrieves Webex settings from the WordPress options, checks if the client ID and client secret are present,
	 * and updates the 'wemeet_webex_auth_prepare' option accordingly.
	 *
	 * @return bool True if credentials are configured, false otherwise.
	 */
	public static function is_webex_auth_prepared() {
		$status = false;

		// Get webex settings from options.
		$webex_settings = get_option( 'wemeet_webex_settings', true );

		if ( is_array( $webex_settings ) && ! empty( $webex_settings ) ) {
			// Extract API key and API secret from settings.
			$client_id     = $webex_settings['client_id'] ? $webex_settings['client_id'] : '';
			$client_secret = $webex_settings['client_secret'] ? $webex_settings['client_secret'] : '';

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

		return $status;
	}

	/**
	 * Clear access token if Webex auth is not prepared.
	 *
	 * @return void
	 */
	public static function clear_token_if_not_prepared() {
		if ( ! self::is_webex_auth_prepared() ) {
			$current_user_id = get_current_user_id();
			update_user_meta( $current_user_id, 'wemeet_webex_access_token', '' );
		}
	}
}
