<?php
/**
 * MailerLite API class.
 *
 * @package Masteriyo\Addons\MailerLiteIntegration\API
 *
 * @since 2.14.4
 */
namespace Masteriyo\Addons\MailerLiteIntegration\API;

defined( 'ABSPATH' ) || exit;


use Masteriyo\EmailMarketingAndCRM\APIClient;

/**
 * MailerLite API class.
 *
 * @since 2.14.4
 */
class API extends APIClient {

	/**
	 * Access token.
	 *
	 * @since 2.14.4
	 *
	 * @var string
	 */
	private $api_key;

	/**
	 * API endpoint.
	 *
	 * @since 2.14.4
	 *
	 * @var string
	 */
	private $endpoint = MASTERIYO_MAILERLITE_INTEGRATION_BASE_URL;

	/**
	 * Constructor for API.
	 *
	 * @since 2.14.4
	 *
	 * @param string $api_key The API key.
	 */
	public function __construct( string $api_key ) {
		parent::__construct( $this->endpoint );

		$this->api_key = $api_key;

		$this->set_bearer_token( $this->api_key );

		$this->set_header( 'User-Agent', 'Masteriyo/' . MASTERIYO_VERSION . '; ' . get_bloginfo( 'url' ) );
	}

	/**
	 * Validate API key.
	 *
	 * @since 2.14.4
	 *
	 * @param string $api_key The API key.
	 *
	 * @return bool Returns true if the API key is valid, false otherwise.
	 */
	public function validate_api_key( $api_key ) {
		$this->set_bearer_token( $api_key );

		$result = $this->auth_test();

		if ( is_wp_error( $result ) ) {
			return false;
		}

		return isset( $result['data'] );
	}

	/**
	 * Test the API key.
	 *
	 * @since 2.14.4
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function auth_test() {
		return $this->get( 'subscribers', array( 'limit' => 1 ) );
	}

	/**
	 * Get the list of groups.
	 *
	 * @since 2.14.4
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function get_groups() {
		return $this->get( 'groups' );
	}

	/**
	 * Create a new subscriber.
	 *
	 * @since 2.14.4
	 *
	 * @param array $data The subscriber data.
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function create_subscriber( array $data ) {
		return $this->post( 'subscribers', $data );
	}
}
