<?php

namespace AAWP\API;

/**
 * Product Quota Check.
 *
 * @since 3.32.0
 */
class Quota {

	/**
	 * Product Quota Check Endpoint.
	 *
	 * @since 3.32.0
	 *
	 * @var $endpoint The product quota check API endpoint.
	 */
	private $endpoint = 'https://api.getaawp.com/v1/check/quota';

	/**
	 * Initialize.
	 *
	 * @since 3.32.0
	 */
	public function init() {

		if ( defined( 'AAWP_API_URL' ) ) {
			$this->endpoint = AAWP_API_URL . '/check/quota';
		}

		add_action( 'aawp_settings_process', [ $this, 'process' ] );
	}

	/**
	 * Validate the quota refresh button and update the quota.
	 *
	 * @since 3.32.0
	 */
	public function process( $post_data ) {

		if ( 'aawp_aawp_api' !== $post_data['option_page'] || empty( $post_data['aawp_aawp_api']['connect'] ) ) {
			return;
		}

		$key = ! empty( aawp_fs()->_get_license()->secret_key ) ? aawp_fs()->_get_license()->secret_key : '';

		// Remote API Call.
		$response = wp_remote_get(
			$this->endpoint,
			[
				'headers' => [
					'Authorization' => $key,
				],
			]
		);

		$body = wp_remote_retrieve_body( $response );

		if ( json_decode( $body ) === null && json_last_error() !== JSON_ERROR_NONE ) {
			return [ 'error' => 'Invalid JSON response.' ];
		}

		$data = json_decode( $body, true );

		$usage_limit      = isset( $data['api_usage_limit'] ) ? absint( $data['api_usage_limit'] ) : 0;
		$usage_expires_at = isset( $data['api_usage_expiry'] ) ? sanitize_text_field( $data['api_usage_expiry'] ) : '-';

		update_option( 'aawp_products_api_usage_limit', $usage_limit );
		update_option( 'aawp_products_api_usage_expires_at', $usage_expires_at );
	}
}
