<?php
/**
 * Mailchimp API class.
 *
 * @package Masteriyo\Addons\MailchimpIntegration\API
 *
 * @since 2.18.0
 */
namespace Masteriyo\Addons\MailchimpIntegration\API;

defined( 'ABSPATH' ) || exit;


use Masteriyo\EmailMarketingAndCRM\APIClient;

/**
 * Mailchimp API class.
 *
 * @since 2.18.0
 */
class API extends APIClient {

	/**
	 * API key.
	 *
	 * @since 2.18.0
	 *
	 * @var string
	 */
	private $api_key;

	/**
	 * API endpoint.
	 *
	 * @since 2.18.0
	 *
	 * @var string
	 */
	private $endpoint = MASTERIYO_MAILCHIMP_INTEGRATION_BASE_URL;

	/**
	 * Constructor for API.
	 *
	 * @since 2.18.0
	 *
	 * @param string $api_key The API key.
	 */
	public function __construct( string $api_key ) {
		$this->api_key = $api_key;
		$this->set_base_endpoint(); // Set correct endpoint before parent init

		parent::__construct( $this->endpoint );

		$headers = array(
			'Accept'        => 'application/json', // Corrected content type
			'Content-Type'  => 'application/json', // Corrected content type
			'Authorization' => 'apikey ' . $this->api_key,
		);

		foreach ( $headers as $key => $value ) {
			$this->set_header( $key, $value );
		}
	}

	/**
	 * Set base endpoint based on data center in API key.
	 *
	 * @since 2.18.0
	 */
	public function set_base_endpoint() {
		if ( ! empty( $this->api_key ) ) {
			$result         = explode( '-', $this->api_key );
			$this->endpoint = str_replace( '<dc>', $result[1], $this->endpoint );

		}
	}

	/**
	 * Validate an API key.
	 *
	 * @since 2.14.4 [Free]
	 *
	 * @param string $api_key The API key to validate.
	 *
	 * @return boolean True if valid, false otherwise.
	 */
	public function validate_api_key( $api_key ) {
			$temp_client = new self( $api_key );
			$response    = $temp_client->get( '/' );
		if ( is_wp_error( $response ) ) {
			return false;
		}
		if ( isset( $response['account_id'] ) ) {
			return true;
		}
			return false;
	}

	/**
	 * Get audiences list from the API.
	 *
	 * @since 2.18.0
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function get_all_audiences() {
		return $this->get( 'lists' );
	}

	/**
	 * Get groups from the API.
	 *
	 * @since 2.18.0
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function get_groups( $list_id ) {
		return $this->get( "lists/{$list_id}/interest-categories" );
	}


	/**
	 * Get interest from the API.
	 *
	 * @since 2.18.0
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function get_interests( $list_id, $category_id ) {
		return $this->get( "lists/{$list_id}/interest-categories/{$category_id}/interests" );
	}


	/**
	 * Insert the Mailchimp subscriber.
	 *
	 * @since 2.18.0
	 *
	 * @param int $list_id list Id
	 * @param array $data Audience Data
	 *
	 * @return array|\WP_Error The API response or a WP_Error instance.
	 */
	public function create_contact( $list_id, $data = array() ) {
		return $this->post( 'lists/' . $list_id . '/members', $data );
	}




}
