<?php
/**
 * Admin REST API for automation and AI agent compatibility.
 *
 * @package SHC4WC
 */

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

class SHC4WC_REST_API {
	const NAMESPACE = 'shc4wc/v1';

	/** @var self|null */
	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	public function register_routes() {
		register_rest_route(
			self::NAMESPACE,
			'/status',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_status' ),
				'permission_callback' => array( $this, 'can_manage_plugin' ),
			)
		);

		register_rest_route(
			self::NAMESPACE,
			'/orders/(?P<id>\d+)/payment-url',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_order_payment_url' ),
				'permission_callback' => array( $this, 'can_edit_orders' ),
				'args'                => array(
					'id' => array(
						'validate_callback' => static function ( $value ) {
							return is_numeric( $value ) && (int) $value > 0;
						},
					),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE,
			'/orders/(?P<id>\d+)/send-payment-link',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'send_order_payment_link' ),
				'permission_callback' => array( $this, 'can_edit_orders' ),
				'args'                => array(
					'id' => array(
						'validate_callback' => static function ( $value ) {
							return is_numeric( $value ) && (int) $value > 0;
						},
					),
				),
			)
		);
	}

	public function can_manage_plugin() {
		return current_user_can( 'manage_options' );
	}

	public function can_edit_orders() {
		return current_user_can( 'edit_shop_orders' ) || current_user_can( 'manage_woocommerce' );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function build_status_payload() {
		$settings = SHC4WC_Plugin::get_settings();
		$gateway  = get_option( 'woocommerce_shc4wc_settings', array() );
		$gateway  = is_array( $gateway ) ? $gateway : array();

		$payload = array(
			'plugin_version'      => defined( 'SHC4WC_VERSION' ) ? SHC4WC_VERSION : '',
			'environment'         => ( isset( $settings['environment'] ) && 'live' === $settings['environment'] ) ? 'live' : 'sandbox',
			'square_connected'    => SHC4WC_Plugin::is_connected(),
			'has_oauth'           => SHC4WC_Plugin::has_oauth_connection(),
			'location_id'         => isset( $settings['location_id'] ) ? (string) $settings['location_id'] : '',
			'gateway_enabled'     => isset( $gateway['enabled'] ) && 'yes' === $gateway['enabled'],
			'onboarding_complete' => class_exists( 'SHC4WC_Onboarding' ) ? SHC4WC_Onboarding::is_completed() : true,
			'woocommerce_active'  => class_exists( 'WooCommerce' ),
			'webhook_url'         => SHC4WC_Plugin::public_api_url( 'shc4wc_webhook' ),
			'ai_assistant_ready'  => class_exists( 'SHC4WC_AI_Assistant' ) && SHC4WC_AI_Assistant::has_api_key(),
		);

		/**
		 * Filter REST status payload for automation and integrations.
		 *
		 * @param array<string, mixed> $payload Status data.
		 */
		return apply_filters( 'shc4wc_rest_status', $payload );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function get_status( WP_REST_Request $request ) {
		unset( $request );
		return rest_ensure_response( self::build_status_payload() );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_order_payment_url( WP_REST_Request $request ) {
		if ( ! class_exists( 'WooCommerce' ) || ! class_exists( 'SHC4WC_Pay_For_Order' ) ) {
			return new WP_Error( 'shc4wc_no_woocommerce', __( 'WooCommerce is not active.', 'payments-connect-square' ), array( 'status' => 400 ) );
		}

		$order = wc_get_order( (int) $request['id'] );
		if ( ! $order ) {
			return new WP_Error( 'shc4wc_order_not_found', __( 'Order not found.', 'payments-connect-square' ), array( 'status' => 404 ) );
		}

		return rest_ensure_response(
			array(
				'order_id'       => $order->get_id(),
				'needs_payment'  => $order->needs_payment(),
				'billing_email'  => $order->get_billing_email(),
				'payment_url'    => SHC4WC_Pay_For_Order::get_customer_payment_url( $order ),
				'payment_method' => $order->get_payment_method(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function send_order_payment_link( WP_REST_Request $request ) {
		if ( ! class_exists( 'WooCommerce' ) || ! class_exists( 'SHC4WC_Pay_For_Order' ) ) {
			return new WP_Error( 'shc4wc_no_woocommerce', __( 'WooCommerce is not active.', 'payments-connect-square' ), array( 'status' => 400 ) );
		}

		$order = wc_get_order( (int) $request['id'] );
		if ( ! $order ) {
			return new WP_Error( 'shc4wc_order_not_found', __( 'Order not found.', 'payments-connect-square' ), array( 'status' => 404 ) );
		}

		$result = SHC4WC_Pay_For_Order::send_payment_link_for_order( $order );
		if ( is_wp_error( $result ) ) {
			return new WP_Error(
				$result->get_error_code(),
				$result->get_error_message(),
				array( 'status' => 400 )
			);
		}

		return rest_ensure_response(
			array(
				'success'        => true,
				'order_id'       => $order->get_id(),
				'billing_email'  => $order->get_billing_email(),
				'payment_url'    => SHC4WC_Pay_For_Order::get_customer_payment_url( $order ),
				'message'        => __( 'Payment link emailed to customer.', 'payments-connect-square' ),
			)
		);
	}
}
