<?php
/**
 * Features API
 */

defined( 'ABSPATH' ) || exit;

class GPSIC_Features_API extends GPSIC_Notifications {

	public function get_features( $slug = 'speed-test' ) {

		// Cloud-bound: do not fetch until the user has explicitly opted in (R3).
		if ( function_exists( 'speeinch_can_collect_data' ) && ! speeinch_can_collect_data() ) {
			return array();
		}

		$url      = esc_url( SPEEINCH_API_BASE_URL . '/wp-json/features-api/v1/area/' . $slug );
		$response = wp_remote_get( $url );

		if ( is_wp_error( $response ) ) {

			$error_message = $response->get_error_message();
			wp_send_json_error( $error_message );

		}

		$response = wp_remote_retrieve_body( $response );
		$response = json_decode( $response, true );

		if ( ! is_array( $response ) ) {
			$response = array();
		}

		return $response;
	}

	public function subscribe( $post = array() ) {
		// Cloud-bound: do not POST until the user has explicitly opted in (R3).
		if ( function_exists( 'speeinch_can_collect_data' ) && ! speeinch_can_collect_data() ) {
			return array(
				'success' => false,
				'message' => __( 'Connect to enable this feature.', 'speed-in-china' ),
			);
		}

		$url = esc_url( SPEEINCH_API_BASE_URL . '/wp-json/features-api/v1/subscriber/tag' );

		$first_name    = isset( $post['fname'] ) ? sanitize_text_field( $post['fname'] ) : '';
		$last_name     = isset( $post['lname'] ) ? sanitize_text_field( $post['lname'] ) : '';
		$email_address = sanitize_text_field( $post['email'] );
		$area_slug     = sanitize_text_field( $post['area_slug'] );
		$tags          = $post['features'];
		$message       = isset( $post['message'] ) ? sanitize_textarea_field( $post['message'] ) : '';

		$response = wp_remote_post(
			$url,
			array(
				'body' => array(
					'first_name'    => $first_name,
					'last_name'     => $last_name,
					'email_address' => $email_address,
					'tags'          => $tags,
					'area_slug'     => $area_slug,
					'message'       => $message,
				),
			)
		);

		if ( is_wp_error( $response ) ) {

			$error_message = $response->get_error_message();
			wp_send_json_error( $error_message );

		}

		return json_decode( wp_remote_retrieve_body( $response ), true );
	}
}
