<?php
/**
 * Admin interface and settings
 *
 * @package BubblaV_Chat
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin class
 */
class Bubblav_Admin {

	/**
	 * Add admin menu item
	 *
	 * @return void
	 */
	public function add_admin_menu() {
		add_options_page(
			esc_html__( 'BubblaV Chat Settings', 'bubblav-chat' ),
			esc_html__( 'BubblaV Chat', 'bubblav-chat' ),
			'manage_options',
			'bubblav-chat',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Register settings
	 *
	 * @return void
	 */
	public function register_settings() {
		register_setting( 'bubblav_settings', 'bubblav_website_id', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'bubblav_settings', 'bubblav_connection_status', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'bubblav_settings', 'bubblav_site_url', array( 'sanitize_callback' => 'esc_url_raw' ) );
		register_setting( 'bubblav_settings', 'bubblav_site_name', array( 'sanitize_callback' => 'sanitize_text_field' ) );
		register_setting( 'bubblav_settings', 'bubblav_is_woocommerce', array( 'sanitize_callback' => 'sanitize_text_field' ) );
	}

	/**
	 * Enqueue admin assets
	 *
	 * @param string $hook Current admin hook.
	 * @return void
	 */
	public function enqueue_admin_assets( $hook ) {
		// Only load on our settings page.
		if ( 'settings_page_bubblav-chat' !== $hook ) {
			return;
		}

		// Enqueue admin CSS.
		wp_enqueue_style(
			'bubblav-admin',
			BUBBLAV_PLUGIN_URL . 'admin/css/bubblav-admin.css',
			array(),
			BUBBLAV_VERSION
		);

		// Enqueue admin JS.
		wp_enqueue_script(
			'bubblav-admin',
			BUBBLAV_PLUGIN_URL . 'admin/js/bubblav-admin.js',
			array( 'jquery' ),
			BUBBLAV_VERSION,
			true
		);

		// Localize script.
		wp_localize_script(
			'bubblav-admin',
			'bubblavAdmin',
			array(
				'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
				'nonce'         => wp_create_nonce( 'bubblav_admin' ),
				'isConnected'   => get_option( 'bubblav_connection_status' ) === 'connected',
				'websiteId'     => get_option( 'bubblav_website_id', '' ),
				'siteUrl'       => home_url(),
				'siteName'      => get_bloginfo( 'name' ),
				'isWooCommerce' => class_exists( 'WooCommerce' ) ? '1' : '0',
			)
		);
	}

	/**
	 * Render settings page
	 *
	 * @return void
	 */
	public function render_settings_page() {
		// Security: Check user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'bubblav-chat' ) );
		}

		// Get connection status.
		$is_connected   = get_option( 'bubblav_connection_status' ) === 'connected';
		$website_id     = get_option( 'bubblav_website_id', '' );
		$site_url       = home_url();
		$site_name      = get_bloginfo( 'name' );
		$is_woocommerce = class_exists( 'WooCommerce' );

		// Load settings view.
		include BUBBLAV_PLUGIN_DIR . 'admin/views/settings-page.php';
	}

	/**
	 * Save settings
	 *
	 * @return void
	 */
	public function save_settings() {
		// Verify nonce.
		if ( ! isset( $_POST['bubblav_nonce'] ) ) {
			wp_die( esc_html__( 'Security check failed', 'bubblav-chat' ) );
		}

		// Sanitize and unslash the nonce value.
		$nonce_value = sanitize_key( wp_unslash( $_POST['bubblav_nonce'] ) );
		if ( ! wp_verify_nonce( $nonce_value, 'bubblav_settings_save' ) ) {
			wp_die( esc_html__( 'Security check failed', 'bubblav-chat' ) );
		}

		// Check capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'bubblav-chat' ) );
		}

		// Get website ID from OAuth callback.
		$website_id = isset( $_POST['bubblav_website_id'] )
			? sanitize_text_field( wp_unslash( $_POST['bubblav_website_id'] ) )
			: '';

		// Get auth token for uninstall API calls (base64 encoded).
		$auth_token = isset( $_POST['bubblav_auth_token'] )
			? sanitize_text_field( wp_unslash( $_POST['bubblav_auth_token'] ) )
			: '';

		// Get original state for CSRF validation.
		$client_state = isset( $_POST['state'] )
			? sanitize_text_field( wp_unslash( $_POST['state'] ) )
			: '';

		if ( empty( $website_id ) ) {
			add_settings_error(
				'bubblav_messages',
				'bubblav_error',
				esc_html__( 'Connection failed. Missing website ID.', 'bubblav-chat' ),
				'error'
			);
			set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
			wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
			exit;
		}

		// Store connection data.
		update_option( 'bubblav_website_id', $website_id );
		update_option( 'bubblav_connection_status', 'connected' );
		update_option( 'bubblav_site_url', home_url() );
		update_option( 'bubblav_site_name', get_bloginfo( 'name' ) );
		update_option( 'bubblav_is_woocommerce', class_exists( 'WooCommerce' ) ? '1' : '0' );

		// Store auth token encrypted for uninstall API calls.
		if ( ! empty( $auth_token ) ) {
			update_option( 'bubblav_auth_token', $this->encrypt_api_key( $auth_token ) );
		}

		add_settings_error(
			'bubblav_messages',
			'bubblav_success',
			esc_html__( 'Connected successfully! Your chat widget is now active.', 'bubblav-chat' ),
			'success'
		);

		set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
		wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
		exit;
	}

	/**
	 * Disconnect from BubblaV
	 *
	 * Calls the backend API to deactivate integrations and delete the website,
	 * then clears local connection data.
	 *
	 * @return void
	 */
	public function disconnect() {
		// Verify nonce.
		if ( ! isset( $_POST['bubblav_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['bubblav_nonce'] ), 'bubblav_disconnect' ) ) {
			wp_die( esc_html__( 'Security check failed', 'bubblav-chat' ) );
		}

		// Check capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'bubblav-chat' ) );
		}

		// Get connection details.
		$website_id = get_option( 'bubblav_website_id', '' );
		$site_url   = get_option( 'bubblav_site_url', home_url() );
		$auth_token = get_option( 'bubblav_auth_token', '' );

		// Call backend API to disconnect.
		if ( ! empty( $website_id ) && ! empty( $auth_token ) ) {
			// Decrypt auth token.
			$api_token = $this->decrypt_api_key( $auth_token );

			if ( ! empty( $api_token ) ) {
				// Call disconnect endpoint.
				wp_remote_post(
					BUBBLAV_API_URL . '/api/integrations/wordpress-plugin/disconnect',
					array(
						'body'    => wp_json_encode(
							array(
								'website_id' => $website_id,
								'site_url'   => $site_url,
							)
						),
						'headers' => array(
							'Content-Type'  => 'application/json',
							'Authorization' => 'Bearer ' . $api_token,
						),
						'timeout'   => 30,
						'sslverify' => defined( 'BUBBLAV_SSL_VERIFY' ) ? BUBBLAV_SSL_VERIFY : true,
					)
				);
			}
		}

		// Clear local connection data.
		delete_option( 'bubblav_website_id' );
		delete_option( 'bubblav_auth_token' );
		delete_option( 'bubblav_site_url' );
		delete_option( 'bubblav_site_name' );
		delete_option( 'bubblav_is_woocommerce' );
		update_option( 'bubblav_connection_status', 'disconnected' );

		add_settings_error(
			'bubblav_messages',
			'bubblav_success',
			esc_html__( 'Disconnected successfully. The chat widget has been removed from your site.', 'bubblav-chat' ),
			'success'
		);

		set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
		wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
		exit;
	}

	/**
	 * Start OAuth flow
	 *
	 * @return void
	 */
	public function start_oauth() {
		// Verify nonce.
		if ( ! isset( $_POST['bubblav_nonce'] ) ) {
			wp_die( esc_html__( 'Security check failed - nonce missing', 'bubblav-chat' ) );
		}

		// Sanitize and unslash the nonce value before verification.
		$nonce_value = sanitize_key( wp_unslash( $_POST['bubblav_nonce'] ) );
		if ( ! wp_verify_nonce( $nonce_value, 'bubblav_start_oauth' ) ) {
			wp_die( esc_html__( 'Security check failed - nonce invalid', 'bubblav-chat' ) );
		}

		// Check capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'bubblav-chat' ) );
		}

		// Generate and store state for CSRF protection.
		$state = wp_create_nonce( 'bubblav_oauth_state' );
		set_transient( 'bubblav_oauth_state', $state, 30 * MINUTE_IN_SECONDS );

		// Check if WooCommerce is enabled.
		$is_woocommerce = class_exists( 'WooCommerce' ) ? '1' : '0';

		// Build OAuth URL.
		$redirect_uri = admin_url( 'admin-post.php?action=bubblav_oauth_callback' );
		$oauth_url = add_query_arg(
			array(
				'site_url'        => home_url(),
				'site_name'       => get_bloginfo( 'name' ),
				'redirect_uri'    => $redirect_uri,
				'state'           => $state,
				'is_woocommerce'  => $is_woocommerce,
			),
			'https://www.bubblav.com/api/integrations/wordpress-plugin/oauth'
		);

		// Add BubblaV host to allowed redirect hosts for OAuth.
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_bubblav_host' ) );
		wp_safe_redirect( $oauth_url );
		exit;
	}

	/**
	 * Allow BubblaV host for safe redirect
	 *
	 * @param array $hosts Allowed hosts.
	 * @return array Modified allowed hosts.
	 */
	public function allow_bubblav_host( $hosts ) {
		$hosts[] = 'www.bubblav.com';
		$hosts[] = 'bubblav.com';
		$hosts[] = 'test-app2.nport.link';
		return $hosts;
	}

	/**
	 * Handle OAuth callback from BubblaV
	 *
	 * @return void
	 */
	public function oauth_callback() {
		// Check user capabilities first.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'bubblav-chat' ) );
		}

		// Get OAuth parameters from query string.
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- OAuth uses state parameter for CSRF.
		$website_id   = isset( $_GET['website_id'] ) ? sanitize_text_field( wp_unslash( $_GET['website_id'] ) ) : '';
		$status       = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
		$error        = isset( $_GET['error'] ) ? sanitize_text_field( wp_unslash( $_GET['error'] ) ) : '';
		$client_state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : '';
		$claim_token  = isset( $_GET['claim_token'] ) ? sanitize_text_field( wp_unslash( $_GET['claim_token'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		// State parameter is required for CSRF protection.
		$stored_state = get_transient( 'bubblav_oauth_state' );
		if ( empty( $client_state ) || empty( $stored_state ) || $client_state !== $stored_state ) {
			wp_die( esc_html__( 'Security check failed. Invalid or missing state parameter.', 'bubblav-chat' ) );
		}

		// Clean up transients.
		delete_transient( 'bubblav_oauth_state' );
		delete_transient( 'bubblav_oauth_user_id' );

		// Handle errors.
		if ( $error ) {
			add_settings_error(
				'bubblav_messages',
				'bubblav_error',
				esc_html__( 'Connection failed: ', 'bubblav-chat' ) . esc_html( $error ),
				'error'
			);
			set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
			wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
			exit;
		}

		// Handle successful connection.
		if ( 'connected' === $status && ! empty( $website_id ) ) {
			$auth_token = '';

			// Exchange claim token for actual auth token via server-side POST request.
			if ( ! empty( $claim_token ) ) {
				$claim_response = wp_remote_post(
					'https://www.bubblav.com/api/integrations/wordpress-plugin/claim-token',
					array(
						'body'    => wp_json_encode(
							array(
								'claim_token' => $claim_token,
								'website_id'  => $website_id,
							)
						),
						'headers' => array(
							'Content-Type' => 'application/json',
						),
						'timeout' => 15,
					)
				);

				if ( ! is_wp_error( $claim_response ) && wp_remote_retrieve_response_code( $claim_response ) === 200 ) {
					$response_body = json_decode( wp_remote_retrieve_body( $claim_response ), true );
					if ( isset( $response_body['auth_token'] ) ) {
						$auth_token = $response_body['auth_token'];
					}
				}
			}

			// If we couldn't get the auth token, redirect with error.
			if ( empty( $auth_token ) ) {
				add_settings_error(
					'bubblav_messages',
					'bubblav_error',
					esc_html__( 'Connection failed. Could not exchange authorization token.', 'bubblav-chat' ),
					'error'
				);
				set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
				wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
				exit;
			}

			// Store connection data.
			update_option( 'bubblav_website_id', $website_id );
			update_option( 'bubblav_connection_status', 'connected' );
			update_option( 'bubblav_site_url', home_url() );
			update_option( 'bubblav_site_name', get_bloginfo( 'name' ) );
			update_option( 'bubblav_is_woocommerce', class_exists( 'WooCommerce' ) ? '1' : '0' );

			// Store auth token encrypted for uninstall API calls.
			update_option( 'bubblav_auth_token', $this->encrypt_api_key( $auth_token ) );

			// Store api_token for REST API authentication (unencrypted for database lookup).
			update_option( 'bubblav_api_token', $auth_token );

			add_settings_error(
				'bubblav_messages',
				'bubblav_success',
				esc_html__( 'Connected successfully! Your chat widget is now active.', 'bubblav-chat' ),
				'success'
			);

			set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
			wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
			exit;
		}

		// If we get here, something went wrong.
		add_settings_error(
			'bubblav_messages',
			'bubblav_error',
			esc_html__( 'Connection failed. Invalid response from BubblaV.', 'bubblav-chat' ),
			'error'
		);
		set_transient( 'bubblav_settings_errors', get_settings_errors(), 30 );
		wp_safe_redirect( admin_url( 'options-general.php?page=bubblav-chat' ) );
		exit;
	}

	/**
	 * Show admin notices
	 *
	 * @return void
	 */
	public function show_admin_notices() {
		// Only show on our settings page.
		if ( isset( $_GET['page'] ) && 'bubblav-chat' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page parameter, not processing form data.
			$errors = get_transient( 'bubblav_settings_errors' );

			if ( $errors ) {
				foreach ( $errors as $error ) {
					$class = isset( $error['type'] ) && 'success' === $error['type'] ? 'notice-success' : 'notice-error';
					printf(
						'<div class="notice %s is-dismissible"><p>%s</p></div>',
						esc_attr( $class ),
						esc_html( $error['message'] )
					);
				}
				delete_transient( 'bubblav_settings_errors' );
			}
		}
	}

	/**
	 * Encrypt API key (placeholder for future use)
	 *
	 * @param string $api_key API key to encrypt.
	 * @return string Encrypted API key.
	 */
	private function encrypt_api_key( $api_key ) {
		// Use WordPress AUTH_KEY for encryption.
		$key = AUTH_KEY;
		$iv  = substr( hash( 'sha256', AUTH_SALT ), 0, 16 );
		return base64_encode( openssl_encrypt( $api_key, 'AES-256-CBC', $key, 0, $iv ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}

	/**
	 * Decrypt API key (placeholder for future use)
	 *
	 * @param string $encrypted Encrypted API key.
	 * @return string Decrypted API key.
	 */
	private function decrypt_api_key( $encrypted ) {
		$key = AUTH_KEY;
		$iv  = substr( hash( 'sha256', AUTH_SALT ), 0, 16 );
		return openssl_decrypt( base64_decode( $encrypted ), 'AES-256-CBC', $key, 0, $iv ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
	}
}
