<?php
/**
 * Deactivation Feedback — WordPress AJAX Handler
 *
 * Handles all server-side AJAX actions for the deactivation feedback modal.
 * Proxies requests to the Captain Data remote API so the browser never
 * calls the external endpoint directly (avoids CORS and exposes nothing).
 *
 * Actions registered:
 *   cwk_deactive_count  — count-only call (Submit Like it / Skip)
 *   cwk_deactive_detail — full detail call (Submit Not Like it)
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes/admin
 * @since      1.0.0
 */

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

if ( ! class_exists( 'Captwiki_Deactivate_Ajax' ) ) {

	/**
	 * Captwiki_Deactivate_Ajax
	 *
	 * Registers wp_ajax_ hooks and proxies deactivation data to the
	 * Captain Data remote API using wp_remote_post().
	 *
	 * @since 1.0.0
	 */
	class Captwiki_Deactivate_Ajax {

		/**
		 * Remote API base URL for deactivation endpoints.
		 *
		 * @since 1.0.0
		 * @var string
		 */
		public $deactive_url = '';

		/**
		 * Singleton instance.
		 *
		 * @since 1.0.0
		 * @var Captwiki_Deactivate_Ajax
		 */
		private static $instance;

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

		/**
		 * Constructor — register AJAX hooks.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			$this->deactive_url = CAPTWIKI_API_BASE;
			add_action( 'wp_ajax_cwk_deactive_count',  array( $this, 'handle_count' ) );
			add_action( 'wp_ajax_cwk_deactive_detail', array( $this, 'handle_detail' ) );
		}

		/**
		 * Verify the AJAX nonce and capability, then die on failure.
		 *
		 * @since  1.0.0
		 *
		 * @return void
		 */
		private function verify_request() {
			check_ajax_referer( 'cwk_deactivate_nonce', 'nonce' );

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

		/**
		 * AJAX handler: count-only deactivation ping.
		 *
		 * Fires on Submit (Like it) and Skip & Deactivate.
		 * Sends a POST to v1/captwiki/deactive_count with no body.
		 *
		 * @since  1.0.0
		 *
		 * @return void
		 */
		public function handle_count() {
			$this->verify_request();

			$endpoint = $this->deactive_url . 'v1/captwiki/deactive_count';

			wp_remote_post(
				$endpoint,
				array(
					'timeout'  => 10,
					'blocking' => false,
					'headers'  => array(
						'Content-Type' => 'application/json',
					),
				)
			);

			wp_send_json_success();
		}

		/**
		 * AJAX handler: full deactivation detail submission.
		 *
		 * Fires on Submit (Like it) and Submit (Not Like it).
		 * Sends a POST to v1/captwiki/deactive with all feedback fields,
		 * site info, versions, and date.
		 *
		 * @since  1.0.0
		 *
		 * @return void
		 */
		public function handle_detail() {
			$this->verify_request();

			global $wp_version;

			$like_it    = isset( $_POST['like_it'] )    ? sanitize_text_field( wp_unslash( $_POST['like_it'] ) )     : 'like';
			$message    = isset( $_POST['message'] )    ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
			$issue_type = isset( $_POST['issue_type'] ) ? sanitize_text_field( wp_unslash( $_POST['issue_type'] ) )  : '';

			$payload = array(
				'wp_version'  => $wp_version,
				'php_version' => PHP_VERSION,
				'site_url'    => esc_url( home_url( '/' ) ),
				'like_it'     => $like_it,
				'message'     => $message,
				'issue_type'  => $issue_type,
				'date'        => gmdate( 'Y-m-d\TH:i:s\Z' ),
			);

			$endpoint = $this->deactive_url . 'v1/captwiki/deactive';

			wp_remote_post(
				$endpoint,
				array(
					'timeout'  => 10,
					'blocking' => false,
					'headers'  => array(
						'Content-Type' => 'application/json',
					),
					'body'     => wp_json_encode( $payload ),
				)
			);

			wp_send_json_success();
		}
	}

	Captwiki_Deactivate_Ajax::get_instance();
}
