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

defined( 'ABSPATH' ) || exit;


use Masteriyo\EmailMarketingAndCRM\APIClient;

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

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

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

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

		$this->access_token = $access_token;

		$this->set_bearer_token( $this->access_token );
	}


	/**
	 * Validate access token.
	 *
	 * @since 2.14.4
	 *
	 * @param string $access_token The access token.
	 *
	 * @return bool Returns true if the access token is valid, false otherwise.
	 */
	public function validate_access_token( $access_token ) {
		$this->set_bearer_token( $access_token );
		$result = $this->auth_test();

		return ! is_wp_error( $result ) && isset( $result['results'] );
	}

	/**
	 * Tests the access token.
	 *
	 * @since 2.14.4
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function auth_test() {
		return $this->get( '/crm/v3/objects/contacts', array( 'limit' => 1 ) );
	}

	/**
	 * Get the lists from the API.
	 *
	 * @since 2.14.4
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function get_lists() {
		return $this->post(
			'/crm/v3/lists/search',
			array(
				'offset'          => 0,
				'processingTypes' => array( 'MANUAL', 'SNAPSHOT' ),
			)
		);
	}

	/**
	 * Create a new contact.
	 *
	 * @since 2.14.4
	 *
	 * @param array $data The contact data.
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function create_contact( array $data ) {
		return $this->post( '/crm/v3/objects/contacts', $data );
	}

	/**
	 * Add a record to a list.
	 *
	 * @since 2.14.4
	 *
	 * @param string $record_id The ID of the record.
	 * @param string $list_id   The ID of the list.
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function add_to_list( $record_id, $list_id ) {
		$data = array(
			$record_id,
		);

		return $this->put( '/crm/v3/lists/' . $list_id . '/memberships/add', $data );
	}
}
