<?php
/**
 * Simple Webhook Simulator for Square
 *
 * @package FunnelKit_Square
 */

namespace FKWCSQ\Includes\Webhooks;

use FKWCSQ\Includes\Logger;
use FKWCSQ\Includes\Traits\Instance;

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

/**
 * Simple Webhook Simulator Class
 */
class Simple_Webhook_Simulator {
	use Instance;

	/**
	 * Initialize the simulator
	 */
	public static function init() {
		add_action( 'wp_ajax_fkwcsq_simulate_webhook', array( __CLASS__, 'handle_simulate_webhook' ) );
	}


	/**
	 * Handle webhook simulation AJAX request
	 */
	public static function handle_simulate_webhook() {
		// Check user permissions first
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Not authorized', 403 );
			return;
		}

		// Verify nonce
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'fkwcsq-admin' ) ) {
			wp_send_json_error( 'Invalid nonce', 403 );
			return;
		}

		// Check if Square is configured
		if ( ! \FKWCSQ\Square::is_configured() ) {
			wp_send_json_error( 'Square is not configured' );
			return;
		}

		try {
			// Get current settings for location ID
			$settings    = get_option( 'fkwcsq_settings', array() );
			$is_sandbox  = \FKWCSQ\Square::is_sandbox_mode();
			$location_id = $is_sandbox ?
				( $settings['sandbox_location_id'] ?? 'sandbox_location_id_not_set' ) :
				( $settings['location_id'] ?? 'production_location_id_not_set' );

			// Create realistic webhook data
			$webhook_data = array(
				'type'       => 'payment.updated',
				'data'       => array(
					'object' => array(
						'payment' => array(
							'id'                  => 'sim_' . uniqid(),
							'status'              => 'COMPLETED',
							'amount_money'        => array(
								'amount'   => 1000,
								'currency' => 'USD',
							),
							'location_id'         => $location_id,
							'created_at'          => gmdate( 'Y-m-d\TH:i:s\Z' ),
							'updated_at'          => gmdate( 'Y-m-d\TH:i:s\Z' ),
							'receipt_number'      => 'TEST-RECEIPT-' . wp_rand( 1000, 9999 ),
							'order_id'            => 'test_order_' . uniqid(),
							'reference_id'        => '', // Empty to allow order creation
							'buyer_email_address' => 'test@example.com',
							'billing_address'     => array(
								'first_name'     => 'Test',
								'last_name'      => 'User',
								'address_line_1' => '123 Test St',
								'locality'       => 'Test City',
								'administrative_district_level_1' => 'TS',
								'postal_code'    => '12345',
								'country'        => 'US',
							),
						),
					),
				),
				'event_id'   => 'evt_' . uniqid(),
				'created_at' => gmdate( 'Y-m-d\TH:i:s\Z' ),
			);

			// Log the simulation
			Logger::debug( 'Webhook simulation started: ' . wp_json_encode( $webhook_data ) );

			// Get the webhook URL
			$webhook_url = home_url( '/wp-json/fkwcsq/v1/webhook' );

			// Make HTTP request to the webhook endpoint
			$response = wp_remote_post(
				$webhook_url,
				array(
					'method'  => 'POST',
					'headers' => array(
						'Content-Type' => 'application/json',
						'User-Agent'   => 'Square-Webhook-Simulator/1.0',
					),
					'body'    => wp_json_encode( $webhook_data ),
					'timeout' => 30,
				)
			);

			// Check for errors
			if ( is_wp_error( $response ) ) {
				throw new \Exception( 'HTTP request failed: ' . $response->get_error_message() );
			}

			$response_code = wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );

			// Parse response
			$response_data = json_decode( $response_body, true );
			if ( json_last_error() !== JSON_ERROR_NONE ) {
				$response_data = array( 'raw_response' => $response_body );
			}

			// Log the response
			Logger::debug(
				'Webhook simulation response: ' . wp_json_encode(
					array(
						'code' => $response_code,
						'body' => $response_data,
					)
				)
			);

			// Return success response with webhook details
			wp_send_json_success(
				array(
					'message'       => 'Webhook simulation completed successfully',
					'webhook_data'  => $webhook_data,
					'webhook_url'   => $webhook_url,
					'response_code' => $response_code,
					'response_data' => $response_data,
					'processed_at'  => current_time( 'c' ),
					'status'        => $response_code === 200 ? 'success' : 'warning',
				)
			);

		} catch ( \Exception $e ) {
			Logger::error( 'Webhook simulation error: ' . $e->getMessage() );
			wp_send_json_error( $e->getMessage() );
		}
	}
}
