<?php
/**
 * AJAX handler for saving WooCommerce tokens
 *
 * @package FinalPOS
 * @since 1.0.0
 */

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

/**
 * Class for handling AJAX requests in FinalPOS
 */
class FinalPOS_AJAX {
	/**
	 * Initialize AJAX handlers
	 */
	public static function init() {
		// Register the AJAX handlers for WooCommerce AJAX (wc-ajax)
		add_action( 'wc_ajax_' . FINALPOS_ACTION_SAVE_TOKEN, array( __CLASS__, 'save_wc_token' ) );
		add_action( 'wc_ajax_nopriv_' . FINALPOS_ACTION_SAVE_TOKEN, array( __CLASS__, 'save_wc_token' ) );

		// Directly handle POST requests if needed
		self::maybe_handle_direct_post();
	}

	/**
	 * Check if there are direct POST requests to handle.
	 */
	private static function maybe_handle_direct_post() {
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {

			// Specifically look for WooCommerce API keys
			if ( isset( $_POST['consumer_key'] ) && isset( $_POST['consumer_secret'] ) ) {

				// Get and sanitize the nonce
				$received_nonce = isset( $_REQUEST[ FINALPOS_NONCE_FIELD ] ) ? sanitize_text_field( $_REQUEST[ FINALPOS_NONCE_FIELD ] ) : '';

				// Enhanced nonce verification with fallback
				$valid_nonce = false;

				// First try transient
				if ( ! empty( $received_nonce ) ) {
					$transient_name = FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . $received_nonce;

					if ( get_transient( $transient_name ) === 'valid' ) {
						$valid_nonce = true;
					}
					// Fallback to option storage
					else {
						$last_nonce      = get_option( FINALPOS_OPTION_LAST_NONCE, '' );
						$last_nonce_time = get_option( FINALPOS_OPTION_LAST_NONCE_TIME, 0 );
						$one_hour_ago    = time() - 3600;

						// Check if nonce matches and is within timeframe
						if ( $received_nonce === $last_nonce && $last_nonce_time > $one_hour_ago ) {
							$valid_nonce = true;
						}
					}
				}

				// Verify nonce
				if ( ! $valid_nonce ) {
					return;
				}

				// Process and save the keys
				$consumer_key    = sanitize_text_field( $_POST['consumer_key'] );
				$consumer_secret = sanitize_text_field( $_POST['consumer_secret'] );

				update_option( FINALPOS_OPTION_CONSUMER_KEY, $consumer_key );
				update_option( FINALPOS_OPTION_CONSUMER_SECRET, $consumer_secret );
				update_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_SETTINGS );

				// Clean up the transient after successful use
				if ( ! empty( $received_nonce ) ) {
					delete_transient( FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . $received_nonce );
				}
			}
		}
	}

	/**
	 * Save WooCommerce token from AJAX request
	 *
	 * @return void
	 */
	public static function save_wc_token() {
		// TODO: Should be another approach to verify the nonce using WP API
		// Get and sanitize the nonce.
		$received_nonce = isset( $_REQUEST[ FINALPOS_NONCE_FIELD ] ) ? sanitize_text_field( $_REQUEST[ FINALPOS_NONCE_FIELD ] ) : '';

		// Enhanced nonce verification with fallback.
		$valid_nonce = false;

		// First try transient.
		if ( ! empty( $received_nonce ) ) {
			$transient_name = FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . $received_nonce;

			if ( get_transient( $transient_name ) === 'valid' ) {
				$valid_nonce = true;
			}
			// Fallback to option storage
			else {
				$last_nonce      = get_option( FINALPOS_OPTION_LAST_NONCE, '' );
				$last_nonce_time = get_option( FINALPOS_OPTION_LAST_NONCE_TIME, 0 );
				$one_hour_ago    = time() - 3600;

				// Check if nonce matches and is within timeframe
				if ( $received_nonce === $last_nonce && $last_nonce_time > $one_hour_ago ) {
					$valid_nonce = true;
				}
			}
		}

		// Verify nonce
		if ( ! $valid_nonce ) {
			wp_send_json_error( __( 'Security check failed.', 'finalpos' ), 403 );
			return;
		}

		// TODO: Should be another approach to verify the request method using WP API
		// Check if the request method is POST
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
			wp_send_json_error( __( 'Invalid request method.', 'finalpos' ), 405 );
			return; // Exit the function after sending the error response
		}

		// TODO: Use WP API to read the JSON payload
		// Read the JSON payload
		$json = file_get_contents( 'php://input' );
		$data = json_decode( $json, true );

		if ( $data !== null && isset( $data['consumer_key'] ) && isset( $data['consumer_secret'] ) ) {
			$consumer_key    = sanitize_text_field( $data['consumer_key'] );
			$consumer_secret = sanitize_text_field( $data['consumer_secret'] );

			if ( empty( $consumer_key ) || empty( $consumer_secret ) ) {
				update_option( FINALPOS_OPTION_ERROR, __( 'Consumer key and secret cannot be empty.', 'finalpos' ) );
				wp_send_json_error( __( 'Invalid consumer key or secret.', 'finalpos' ), 400 );
				return; // Exit the function after sending the error response
			}

			// Save the Consumer Key and Consumer Secret separately
			update_option( FINALPOS_OPTION_CONSUMER_KEY, $consumer_key );
			update_option( FINALPOS_OPTION_CONSUMER_SECRET, $consumer_secret );

			// Save the combined token (used by some parts of the plugin)
			$combined = $consumer_key . '&&&' . $consumer_secret;
			update_option( FINALPOS_OPTION_TOKEN, $combined );

			// Clear any previous errors
			update_option( FINALPOS_OPTION_ERROR, '' );

			// Always set current stage to settings after successful token save
			update_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_SETTINGS );

			// Clean up the transient after successful use
			delete_transient( FINALPOS_TRANSIENT_AUTH_NONCE_PREFIX . $received_nonce );

			wp_send_json_success( __( 'Consumer key and secret saved successfully.', 'finalpos' ) );

			// doing it here to ensure the api key and secret are actually usable and not old or invalid ones
		} else {
			update_option( FINALPOS_OPTION_ERROR, __( 'Could not connect to WooCommerce store. Please try again.', 'finalpos' ) );
			wp_send_json_error( __( 'Invalid JSON payload.', 'finalpos' ), 400 );
		}
	}
}

// Initialize the AJAX handlers
FinalPOS_AJAX::init();
