<?php
/**
 * Zmeet_Settings API Class
 *
 * This class manages the API functionality for the ZooMeet plugin settings.
 *
 * @package SOVLIX\ZMEET\API
 */

namespace SOVLIX\ZMEET\API;

use WP_REST_Controller;
use WP_REST_Server;
use WP_Error;

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

if ( ! class_exists( 'Zmeet_Settings' ) ) {
	/**
	 * Zmeet_Settings Class
	 */
	class Zmeet_Settings extends WP_REST_Controller {
		/**
		 * Zmeet_Settings constructor
		 */
		public function __construct() {
			$this->namespace = 'zmeet/v2';
			$this->rest_base = 'settings';
		}

		/**
		 * Register REST API routes for settings
		 *
		 * @since 1.0.0
		 */
		public function register_routes() {

			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/zoom',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_zoom_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::EDITABLE,
						'callback'            => array( $this, 'save_zoom_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Set addon routes.
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/addon',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_addon_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::EDITABLE,
						'callback'            => array( $this, 'save_addon_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);

			// Set integration routes.
			register_rest_route(
				$this->namespace,
				'/' . $this->rest_base . '/integration',
				array(
					array(
						'methods'             => WP_REST_Server::READABLE,
						'callback'            => array( $this, 'get_integration_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
					array(
						'methods'             => WP_REST_Server::EDITABLE,
						'callback'            => array( $this, 'save_integration_settings' ),
						'permission_callback' => array( $this, 'check_permissions' ),
					),
				)
			);
		}

		/**
		 * Check if the current user has permission to edit posts.
		 *
		 * This function checks if the current user has the capability to edit posts.
		 * It returns true if the user has the 'edit_posts' capability, and false otherwise.
		 *
		 * @return bool True if the current user can edit posts, false otherwise.
		 */
		public function check_permissions() {
			return current_user_can( 'edit_posts' );
		}

		/**
		 * Retrieves settings.
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		public function get_zoom_settings( $request ) {
			$settings = get_option( 'zmeet_zoom_settings', array() );
			$response = rest_ensure_response( $settings );
			return $response;
		}

		/**
		 * Save Zoom settings.
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		/**
		 * Save Zoom settings.
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		/**
		 * Save Zoom settings.
		 *
		 * @param WP_REST_Request $request Request object.
		 *
		 * @return WP_Error|WP_REST_Response
		 */
		public function save_zoom_settings( $request ) {
			$data = json_decode( $request->get_body() );

			// Validate and sanitize the data.
			$validated_data = $this->validate_and_sanitize_zoom_settings( $data );

			if ( is_wp_error( $validated_data ) ) {
				return $validated_data;
			}

			// Update settings in the options.
			update_option( 'zmeet_zoom_settings', $validated_data );
			set_transient( 'zmeet_zoom_settings_live', true, HOUR_IN_SECONDS );

			// Always delete the old OAuth token and regenerate a fresh one on every save.
			update_option( 'zmeet_zoom_global_oauth_data', '' );

			$account_id    = $validated_data['oauth_account_id'] ?? '';
			$client_id     = $validated_data['oauth_client_id'] ?? '';
			$client_secret = $validated_data['oauth_client_secret'] ?? '';

			if ( ! empty( $account_id ) && ! empty( $client_id ) && ! empty( $client_secret ) ) {
				$zoom_auth = \SOVLIX\ZMEET\Zoom\Zmeet_S2SO_Auth::get_instance();
				$zoom_token = $zoom_auth->generate_and_save_access_token( $account_id, $client_id, $client_secret );

				// Fetch and store zoom users after successful connection.
				if ( ! is_wp_error( $zoom_token ) && function_exists( 'zoomeet_store_zoom_users' ) ) {
					zoomeet_store_zoom_users( \SOVLIX\ZMEET\Zoom\Zmeet_Zoom_Api::instance() );
				}
			} else {
				update_option( 'zmeet_is_server_auth_prepare', 'no' );
			}

			// Also handle SDK status.
			if ( empty( $validated_data['sdk_client_id'] ) || empty( $validated_data['sdk_client_secret'] ) ) {
				update_option( 'zmeet_is_sdk_prepare', 'no' );
			}

			$response = array(
				'zoom_settings_saved' => true,
				'zoom_api_settings'   => $validated_data,
			);

			return rest_ensure_response( $response );
		}



		/**
		 * Validate and sanitize settings.
		 *
		 * @param object $data Zmeet_Settings data.
		 *
		 * @return WP_Error|array Validated and sanitized settings data.
		 */
		private function validate_and_sanitize_zoom_settings( $data ) {
			// Sanitize data before saving.
			$sanitized_data = array(
				'oauth_account_id'          => isset( $data->oauth_account_id ) ? sanitize_text_field( $data->oauth_account_id ) : '',
				'oauth_client_id'           => isset( $data->oauth_client_id ) ? sanitize_text_field( $data->oauth_client_id ) : '',
				'oauth_client_secret'       => isset( $data->oauth_client_secret ) ? sanitize_text_field( $data->oauth_client_secret ) : '',
				'sdk_client_id'             => isset( $data->sdk_client_id ) ? sanitize_text_field( $data->sdk_client_id ) : '',
				'sdk_client_secret'         => isset( $data->sdk_client_secret ) ? sanitize_text_field( $data->sdk_client_secret ) : '',
				'enable_recurring_meeting'  => isset( $data->enable_recurring_meeting ) ? sanitize_text_field( $data->enable_recurring_meeting ) : '',
				'meeting_timezone'          => isset( $data->meeting_timezone ) ? sanitize_text_field( $data->meeting_timezone ) : '',
				'enable_should_register'    => isset( $data->enable_should_register ) ? sanitize_text_field( $data->enable_should_register ) : '',
				'disable_waiting_room'      => isset( $data->disable_waiting_room ) ? sanitize_text_field( $data->disable_waiting_room ) : '',
				'meeting_authentication'    => isset( $data->meeting_authentication ) ? sanitize_text_field( $data->meeting_authentication ) : '',
				'join_before_host'          => isset( $data->join_before_host ) ? sanitize_text_field( $data->join_before_host ) : '',
				'option_mute_participants'  => isset( $data->option_mute_participants ) ? sanitize_text_field( $data->option_mute_participants ) : '',
				'practice_session'          => isset( $data->practice_session ) ? sanitize_text_field( $data->practice_session ) : '',
				'allow_multiple_devices'    => isset( $data->allow_multiple_devices ) ? sanitize_text_field( $data->allow_multiple_devices ) : '',
				'auto_recording'            => isset( $data->auto_recording ) ? sanitize_text_field( $data->auto_recording ) : '',
				'hide_sidebar'              => isset( $data->hide_sidebar ) ? sanitize_text_field( $data->hide_sidebar ) : '',
				'hide_header_footer'        => isset( $data->hide_header_footer ) ? sanitize_text_field( $data->hide_header_footer ) : '',
				'allow_vendor_settings'     => isset( $data->allow_vendor_settings ) ? (bool) $data->allow_vendor_settings : false,
				'option_host_video'         => isset( $data->option_host_video ) ? sanitize_text_field( $data->option_host_video ) : '',
				'option_participants_video' => isset( $data->option_participants_video ) ? sanitize_text_field( $data->option_participants_video ) : '',
				'panelists_video'           => isset( $data->panelists_video ) ? sanitize_text_field( $data->panelists_video ) : '',
				'hd_video'                  => isset( $data->hd_video ) ? sanitize_text_field( $data->hd_video ) : '',
			);

			return $sanitized_data;
		}


		/**
		 * Get addon settings
		 *
		 * @return WP_REST_Response|WP_Error
		 */
		public function get_addon_settings() {
			$settings = get_option( 'zmeet_addons_settings', array() );
			return rest_ensure_response( $settings );
		}

		/**
		 * Get integration settings
		 *
		 * @return WP_REST_Response|WP_Error
		 */
		public function get_integration_settings() {
			$settings = get_option( 'zmeet_integration_settings', array() );
			return rest_ensure_response( $settings );
		}

		/**
		 * Save addon settings
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function save_addon_settings( $request ) {
			$settings = $request->get_param( 'zmeet_addons_settings' );

			if ( ! is_array( $settings ) ) {
				return new WP_Error(
					'invalid_settings',
					__( 'Settings must be an array.', 'zoomeet' ),
					array( 'status' => 400 )
				);
			}

			$updated = update_option( 'zmeet_addons_settings', $settings );

			$response = array(
				'addon_settings_saved' => true,
			);

			return rest_ensure_response( $response );
		}

		/**
		 * Save integration settings
		 *
		 * @param WP_REST_Request $request Request object.
		 * @return WP_REST_Response|WP_Error
		 */
		public function save_integration_settings( $request ) {
			$settings = $request->get_param( 'zmeet_integration_settings' );

			if ( ! is_array( $settings ) ) {
				return new WP_Error(
					'invalid_settings',
					__( 'Settings must be an array.', 'zoomeet' ),
					array( 'status' => 400 )
				);
			}

			$updated = update_option( 'zmeet_integration_settings', $settings );

			$response = array(
				'integration_settings_saved' => true,
			);

			return rest_ensure_response( $response );
		}

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

			$configs = array(
				'zoom_oauth' => array(
					'prepared'  => function_exists( 'zmeet_is_server_auth_prepare' ) ? zmeet_is_server_auth_prepare() : true,
					'connected' => function_exists( 'zmeet_is_zoom_oauth_connected' ) ? zmeet_is_zoom_oauth_connected() : true,
				),
				'zoom_sdk'   => array(
					'prepared' => function_exists( 'zmeet_is_sdk_prepare' ) ? zmeet_is_sdk_prepare() : true,
				),
			);

			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'] ) {
					$notices[] = array(
						'id'    => $id,
						'type'  => 'warning',
						'state' => 'unprepared',
					);
				} elseif ( isset( $status['connected'] ) && ! $status['connected'] ) {
					$notices[] = array(
						'id'    => $id,
						'type'  => 'info',
						'state' => 'unconnected',
					);
				}
			}

			return $notices;
		}
	}
}
