<?php
/**
 * Route handler for account connections.
 *
 * @package    100Prints
 */

class Hundred_Prints_Route_Connect {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route( '100prints/v1', '/connect', [
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this, 'connect_account' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
			[
				'methods'             => WP_REST_Server::DELETABLE,
				'callback'            => [ $this, 'disconnect_account' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
		] );

		register_rest_route( '100prints/v1', '/disconnect', [
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this, 'disconnect_account' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
		] );
	}

	/**
	 * Permission check callback.
	 */
	public function permission_check( $request ) {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Connect a 100Prints account.
	 */
	public function connect_account( $request ) {
		$params = $request->get_json_params();
		$api_key = isset( $params['api_key'] ) ? sanitize_text_field( $params['api_key'] ) : '';

		if ( empty( $api_key ) ) {
			return new WP_Error( '100prints_bad_request', 'Missing API key', [ 'status' => 400 ] );
		}

		$conn_service = new Hundred_Prints_Connection_Service();
		$result = $conn_service->store_key( $api_key );

		if ( ! $result ) {
			return new WP_Error( '100prints_connection_failed', 'Could not verify API Secret Key', [ 'status' => 400 ] );
		}

		return rest_ensure_response( [ 'success' => true ] );
	}

	/**
	 * Disconnect a 100Prints account.
	 */
	public function disconnect_account( $request ) {
		$conn_service = new Hundred_Prints_Connection_Service();
		$conn_service->disconnect();

		return rest_ensure_response( [ 'success' => true ] );
	}
}
