<?php // phpcs:ignore
/**
 * Goodmeet_Admin Class
 *
 * This class defines the administration functionality for the goodmeet plugin.
 *
 * @package SOVLIX\GOODMEET
 */

namespace SOVLIX\GOODMEET;

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

if ( ! class_exists( 'Goodmeet_Admin' ) ) {
	/**
	 * Goodmeet_Admin Class
	 *
	 * Responsible for handling administration-related tasks for the goodmeet plugin.
	 *
	 * @since 1.0.0
	 */
	class Goodmeet_Admin {
		/**
		 * Goodmeet_Admin constructor.
		 *
		 * Initializes the admin class.
		 */
		public function __construct() {
			new Admin\Goodmeet_Menu();

			// Get raw inputs with FILTER_UNSAFE_RAW (no filtering by PHP).
			$code_raw     = filter_input( INPUT_GET, 'code', FILTER_UNSAFE_RAW );
			$page_raw     = filter_input( INPUT_GET, 'page', FILTER_UNSAFE_RAW );
			$state_raw    = filter_input( INPUT_GET, 'state', FILTER_UNSAFE_RAW );
			$platform_raw = filter_input( INPUT_GET, 'platform', FILTER_UNSAFE_RAW );

			// Sanitize inputs with WordPress functions.
			$code     = $code_raw ? sanitize_text_field( $code_raw ) : '';
			$page     = $page_raw ? absint( $page_raw ) : 0;
			$state    = $state_raw ? sanitize_text_field( $state_raw ) : '';
			$platform = $platform_raw ? sanitize_text_field( $platform_raw ) : '';

			$google_meet = Googlemeet\Goodmeet_Meet::get_instance();

			if ( ! empty( $code ) ) {
				if ( 'google-meet' === $platform ) {
					// Handle Google Meet integration.
					if ( ! $google_meet->is_app_permitted() ) {
						$save_token = $google_meet->save_token( $code );

						// Redirect based on whether the app is permitted after saving the token.
						if ( false !== $google_meet->is_app_permitted() ) {
							wp_safe_redirect( admin_url( 'admin.php?page=goodmeet-settings' ) );
						} else {
							wp_safe_redirect( admin_url( 'admin.php?page=goodmeet-settings' ) );
						}
						exit;
					}
				}
			}

			add_filter( 'plugin_action_links', array( $this, 'goodmeet_settings_link' ), 11, 2 );
		}

		/**
		 * Adds a "Settings" link to the plugin actions on the WordPress Plugins page.
		 *
		 * This function is a WordPress filter function that specifically targets the "goodmeet" plugin.
		 *
		 * @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, including the additional "Settings" link if the plugin is "goodmeet".
		 *
		 * @since 1.2.0
		 */
		public function goodmeet_settings_link( $actions, $plugin_file ) {
			if ( 'goodmeet/goodmeet.php' === $plugin_file ) {
				$settings_link = '<a href="' . admin_url( 'admin.php?page=goodmeet-settings' ) . '">' . esc_html__( 'Settings', 'goodmeet' ) . '</a>';
				if ( ! in_array( $settings_link, $actions, true ) ) {
					array_push( $actions, $settings_link );
				}
			}

			return $actions;
		}
	}
}
