<?php
/**
 * WooCommerce API Handler
 *
 * @package FinalPOS
 * @since 1.0.0
 */

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

/**
 * Class for handling WooCommerce API callbacks
 */
class FinalPOS_WC_API {
	/**
	 * Initialize API handlers
	 */
	public static function init() {
		// Register with WooCommerce API
		add_action( 'woocommerce_api_' . FINALPOS_ACTION_SAVE_TOKEN, array( __CLASS__, 'handle_wc_api_callback' ) );

		// Also register with init for direct URL handling
		add_action( 'init', array( __CLASS__, 'maybe_handle_callback' ), 10 );
	}

	/**
	 * Check if we need to handle a callback based on GET parameters.
	 */
	public static function maybe_handle_callback() {

		if ( ( ! empty( $_GET['wc-api'] ) && $_GET['wc-api'] === FINALPOS_ACTION_SAVE_TOKEN ) ||
			( ! empty( $_GET['wc-ajax'] ) && $_GET['wc-ajax'] === FINALPOS_ACTION_SAVE_TOKEN ) ) {
			self::handle_wc_api_callback();
		}
	}

	/**
	 * Handle the WooCommerce API callback for Final POS
	 */
	public static function handle_wc_api_callback() {

		// Check if this is our callback
		$is_our_callback = ( ! empty( $_GET['wc-api'] ) && $_GET['wc-api'] === FINALPOS_ACTION_SAVE_TOKEN ) ||
							( ! empty( $_GET['wc-ajax'] ) && $_GET['wc-ajax'] === FINALPOS_ACTION_SAVE_TOKEN );

		if ( ! $is_our_callback ) {
			error_log( 'FinalPOS: Not our callback' );
			return;
		}

		// Try to read JSON input in case data is coming that way
		$json      = file_get_contents( 'php://input' );
		$json_data = json_decode( $json, true );

		// Determine if we have consumer key and secret from either POST or JSON
		$has_keys_in_post = isset( $_POST['consumer_key'] ) && isset( $_POST['consumer_secret'] ) &&
							! empty( $_POST['consumer_key'] ) && ! empty( $_POST['consumer_secret'] );

		$has_keys_in_json = $json_data !== null && isset( $json_data['consumer_key'] ) && isset( $json_data['consumer_secret'] ) &&
							! empty( $json_data['consumer_key'] ) && ! empty( $json_data['consumer_secret'] );

		if ( $has_keys_in_post ) {
			// Get from POST
			$consumer_key    = sanitize_text_field( $_POST['consumer_key'] );
			$consumer_secret = sanitize_text_field( $_POST['consumer_secret'] );
			self::save_wc_tokens( $consumer_key, $consumer_secret );
		} elseif ( $has_keys_in_json ) {
			// Get from JSON
			$consumer_key    = sanitize_text_field( $json_data['consumer_key'] );
			$consumer_secret = sanitize_text_field( $json_data['consumer_secret'] );
			self::save_wc_tokens( $consumer_key, $consumer_secret );
		} else {
			error_log( 'FinalPOS: No consumer key and secret found in any input' );
		}
	}

	/**
	 * Save WooCommerce API tokens
	 *
	 * @param string $consumer_key The WooCommerce API consumer key
	 * @param string $consumer_secret The WooCommerce API consumer secret
	 * @return bool True on success
	 */
	public static function save_wc_tokens( $consumer_key, $consumer_secret ) {
		error_log( 'FinalPOS: Saving WC tokens - Key: ' . substr( $consumer_key, 0, 5 ) . '... Secret: ' . substr( $consumer_secret, 0, 5 ) . '...' );

		// Save the keys
		update_option( FINALPOS_OPTION_CONSUMER_KEY, $consumer_key );
		update_option( FINALPOS_OPTION_CONSUMER_SECRET, $consumer_secret );

		// Save the combined token value
		$combined = $consumer_key . '&&&' . $consumer_secret;
		update_option( FINALPOS_OPTION_TOKEN, $combined );

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

		// Update the stage
		update_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_SETTINGS );

		// Return success
		return true;
	}
}

// Initialize the WC API handlers
FinalPOS_WC_API::init();
