<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Notifications API
 */
class GPSIC_Notifications {


	function __construct() {
	}

	public function get_latest_notification() {

		// 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 null;
		}

		global $speeinch_fs;

		$plan    = is_object( $speeinch_fs ) ? $speeinch_fs->get_plan() : null;
		$plan_id = ( is_object( $plan ) && isset( $plan->id ) ) ? (int) $plan->id : 0;

		$response = get_transient( 'china_speed_latest_notification' . $plan_id );

		if ( ! empty( $response ) ) {
			return $response;
		}

		$response = wp_remote_get( SPEEINCH_API_BASE_URL . '/wp-json/notification-system-api/v1/notifications/latest?segment=' . $plan_id );

		if ( is_wp_error( $response ) ) {
			return null;
		}

		$response = wp_remote_retrieve_body( $response );

		if ( empty( $response ) ) {
			return null;
		}

		$response = json_decode( $response, true );

		if ( empty( $response ) || ! is_array( $response ) || ! isset( $response['data'] ) ) {
			return null;
		}

		set_transient( 'china_speed_latest_notification' . $plan_id, $response['data'], HOUR_IN_SECONDS );

		return $response['data'];
	}
}
