<?php
/**
 * Onboarding — WordPress AJAX Handler
 *
 * Handles all server-side AJAX actions for the onboarding flow.
 * Registers its own dedicated wp_ajax_ action so the logic stays
 * fully decoupled from the general dashboard AJAX router.
 *
 * On "Allow & Continue": saves the user-meta dismiss flag and proxies
 * anonymous site info to the Captain Data API via wp_remote_post()
 * (non-blocking — the user is never made to wait for the remote call).
 *
 * On "Skip": only the dismiss flag is saved; no data is sent.
 *
 * Actions registered:
 *   captwiki_onboarding_dismiss — main handler (nonce: captwiki_nonce)
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes/admin/ux
 * @since      1.1.3
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Captwiki_Onboarding_Ajax' ) ) {

	/**
	 * Captwiki_Onboarding_Ajax
	 *
	 * Registers the onboarding dismiss AJAX action and proxies
	 * optional site data to the Captain Data onboarding API.
	 *
	 * @since 1.1.3
	 */
	class Captwiki_Onboarding_Ajax {

		/**
		 * Singleton instance.
		 *
		 * @since 1.1.3
		 * @var Captwiki_Onboarding_Ajax
		 */
		private static $instance;

		/**
		 * Initiator — returns the single instance.
		 *
		 * @since  1.1.3
		 *
		 * @return Captwiki_Onboarding_Ajax
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Constructor — register AJAX hook.
		 *
		 * @since 1.1.3
		 */
		public function __construct() {
			add_action( 'wp_ajax_captwiki_onboarding_dismiss', array( $this, 'handle_dismiss' ) );
		}

		/**
		 * AJAX handler: dismiss the onboarding popup.
		 *
		 * Verifies the nonce and capability, saves the per-user dismiss flag,
		 * and — when send_data is truthy — fires a non-blocking POST to the
		 * Captain Data onboarding API with anonymous site info.
		 *
		 * @since  1.1.3
		 *
		 * @return void  Terminates with wp_send_json_success / wp_send_json_error.
		 */
		public function handle_dismiss() {
			check_ajax_referer( 'captwiki_nonce', 'nonce' );

			if ( ! current_user_can( 'manage_options' ) ) {
				wp_send_json_error( array( 'message' => 'Unauthorized.' ), 403 );
			}

			$current_user_id = get_current_user_id();

			if ( ! $current_user_id ) {
				wp_send_json_error( array( 'message' => 'User not logged in.' ), 401 );
			}

			$send_data = isset( $_POST['send_data'] ) ? (bool) sanitize_text_field( wp_unslash( $_POST['send_data'] ) ) : false;

			if ( $send_data ) {
				$this->send_onboarding_data();
			}

			update_user_meta( $current_user_id, 'captwiki_onboarding_dismissed', '1' );

			wp_send_json_success( array( 'message' => 'Onboarding dismissed.' ) );
		}

		/**
		 * Collect anonymous site info and POST it to the Captain Data onboarding API.
		 *
		 * Uses wp_remote_post() with blocking=false so the HTTP call runs in
		 * the background and never delays the AJAX response to the browser.
		 * Failures are silently ignored.
		 *
		 * @since  1.1.3
		 *
		 * @return void
		 */
		private function send_onboarding_data() {
			global $wp_version;

			$server_software = isset( $_SERVER['SERVER_SOFTWARE'] )
				? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) )
				: '';

			$site_data = array(
				'wp_version'  => $wp_version,
				'php_version' => PHP_VERSION,
				'site_url'    => esc_url( home_url( '/' ) ),
				'site_lang'   => get_bloginfo( 'language' ),
				'web_server'  => $server_software,
				'date'        => gmdate( 'Y-m-d\TH:i:s\Z' ),
			);

			wp_remote_post(
				CAPTWIKI_API_BASE . 'v1/captwiki/onboarding',
				array(
					'headers'  => array( 'Content-Type' => 'application/json' ),
					'body'     => wp_json_encode( $site_data ),
					'timeout'  => 15,
					'blocking' => true,
				)
			);
		}
	}

	Captwiki_Onboarding_Ajax::get_instance();
}
