<?php
/**
 * File Path: includes/admin/tabs/license/class-mbs-tab-license-ajax.php
 *
 * License Tab Ajax Handler
 *
 * Owns all four wp_ajax_* and admin_post_* action handlers for the License tab:
 *   · mbs_activate_license    — POST key, calls MBS_License_Client::activate()
 *   · mbs_deactivate_license  — calls MBS_License_Client::deactivate()
 *   · mbs_register_free_key   — POST email, calls MBS_License_Client::register()
 *   · mbs_validate_now        — admin-post, calls MBS_License_Client::validate()
 *
 * All handlers share the same nonce (mbs_license_ajax) except validate_now
 * which uses check_admin_referer( 'mbs_validate_now' ) as a form-POST endpoint.
 *
 * Nonce is localized by MBS_Plugin::enqueue_admin_assets() onto the
 * 'mbs-book-editor' script handle as MBS_License_Ajax.nonce and consumed by
 * admin-license.js. This class does not touch enqueuing.
 *
 * Sprint 9: append payment AJAX handlers (process, status-check, upgrade)
 * to this file only. Do not touch MBS_Tab_License_Render.
 *
 * Contract with parent (MBS_Tab_License):
 *   · register_hooks() is called by the parent at boot time via register().
 *     This class must not call add_action() anywhere except register_hooks().
 *
 * @package    My_Book_Showroom
 * @since      1.0.0
 */

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

class MBS_Tab_License_Ajax {

	/**
	 * Register all wp_ajax_* and admin_post_* hooks.
	 *
	 * Called by MBS_Tab_License::register() at boot time.
	 *
	 */
	public function register_hooks(): void {
		add_action( 'wp_ajax_mbs_activate_license',   array( $this, 'ajax_activate' ) );
		add_action( 'wp_ajax_mbs_deactivate_license', array( $this, 'ajax_deactivate' ) );
		add_action( 'wp_ajax_mbs_register_free_key',  array( $this, 'ajax_register_free_key' ) );
		add_action( 'admin_post_mbs_validate_now',    array( $this, 'validate_now' ) );
	}

	// -------------------------------------------------------------------------
	// AJAX handlers
	// -------------------------------------------------------------------------

	/**
	 * Handle mbs_activate_license AJAX.
	 *
	 * Reads $_POST['key'], sanitizes, and calls MBS_License_Client::activate().
	 * Returns wp_send_json_success on success, wp_send_json_error on failure.
	 *
	 */
	public function ajax_activate(): void {
		check_ajax_referer( 'mbs_license_ajax', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'Insufficient permissions.', 'my-book-showroom' ) );
		}

		$key = sanitize_text_field( wp_unslash( $_POST['key'] ?? '' ) );
		if ( empty( $key ) ) {
			wp_send_json_error( __( 'License key is required.', 'my-book-showroom' ) );
		}

		$client = new \DMRS\MBS\Api\MBS_License_Client();
		$result = $client->activate( $key );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		wp_send_json_success( __( 'License activated successfully.', 'my-book-showroom' ) );
	}

	/**
	 * Handle mbs_deactivate_license AJAX.
	 *
	 * Calls MBS_License_Client::deactivate() which always clears local
	 * credentials regardless of server response (Sprint 8b guarantee).
	 *
	 */
	public function ajax_deactivate(): void {
		check_ajax_referer( 'mbs_license_ajax', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'Insufficient permissions.', 'my-book-showroom' ) );
		}

		$client = new \DMRS\MBS\Api\MBS_License_Client();
		$result = $client->deactivate();

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		wp_send_json_success( __( 'License deactivated successfully.', 'my-book-showroom' ) );
	}

	/**
	 * Handle mbs_register_free_key AJAX.
	 *
	 * Reads $_POST['email'], validates, and calls MBS_License_Client::register().
	 * On success returns { key: 'MBS-FREE-...' } so admin-license.js
	 * can display it and auto-activate.
	 *
	 */
	public function ajax_register_free_key(): void {
		check_ajax_referer( 'mbs_license_ajax', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'Insufficient permissions.', 'my-book-showroom' ) );
		}

		$email = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
		if ( ! is_email( $email ) ) {
			wp_send_json_error( __( 'Please enter a valid email address.', 'my-book-showroom' ) );
		}

		$client = new \DMRS\MBS\Api\MBS_License_Client();
		$result = $client->register( $email );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( $result->get_error_message() );
		}

		wp_send_json_success( array( 'key' => $result['license_key'] ?? '' ) );
	}

	/**
	 * Handle admin-post mbs_validate_now (form-based, non-AJAX).
	 *
	 * Triggers an on-demand validation ping and redirects back to the
	 * license tab. Used by the "Validate now →" link in the stale-ping notice.
	 *
	 */
	public function validate_now(): void {
		check_admin_referer( 'mbs_validate_now' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'my-book-showroom' ) );
		}

		$client = new \DMRS\MBS\Api\MBS_License_Client();
		$client->validate();

		wp_safe_redirect( admin_url( 'admin.php?page=my-book-showroom-settings&tab=dashboard' ) );
		exit;
	}
}
