<?php

namespace Brandy\Newsletter\Providers;

use Brandy\Newsletter\NewsletterProviderInterface;

class MailChimpNewsletterProvider implements NewsletterProviderInterface {
	private $api_key;

	public function __construct( $api_key ) {
		$this->api_key = $api_key;
	}

	public function get_subscriber( string $email ) {
		return null;
	}

	public function get_list() {
		if ( ! $this->api_key ) {
			return array();
		}

		$region = $this->get_region( $this->api_key );

		if ( ! $region ) {
			return array();
		}

		// Check transient cache first (12-hour expiration)
		$cache_key = 'brandy_mailchimp_lists_' . md5( $this->api_key );
		$cached    = get_transient( $cache_key );

		if ( false !== $cached ) {
			return $cached;
		}

		$response = wp_remote_get(
			'https://' . $region . '.api.mailchimp.com/3.0/lists?count=50',
			array(
				'timeout' => 2,
				'headers' => array(
					'Authorization' => 'Basic user:' . $this->api_key,
				),
			)
		);

		if ( ! is_wp_error( $response ) ) {
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
				return array();
			}

			$body = json_decode( wp_remote_retrieve_body( $response ), true );

			if ( ! $body ) {
				return array();
			}

			if ( empty( $body['lists'] ) ) {
				return array();
			}

			$lists = array_map(
				function( $list ) {
					return array(
						'name' => $list['name'],
						'id'   => $list['id'],
					);
				},
				$body['lists']
			);

			// Cache for 12 hours
			set_transient( $cache_key, $lists, 12 * HOUR_IN_SECONDS );

			return $lists;
		} else {
			return array();
		}
	}

	public function add_subscriber( array $args ) {

		$region = $this->get_region( $this->api_key );

		if ( ! $region ) {
			return 'api_key_invalid';
		}

		$url = 'https://' . $region . '.api.mailchimp.com/3.0/lists/' . $args['list_id'] . '/members/';

		if ( ! empty( $args['name'] ) ) {
			$names      = explode( ' ', $args['name'] );
			$last_name  = end( $names );
			$first_name = implode( ' ', array_slice( $names, 0, -1 ) );
		}

		$body = array(
			'email'      => $args['email'],
			'attributes' => array(
				'FIRSTNAME' => $first_name,
				'LASTNAME'  => $last_name,
			),
			'listIds'    => array( intval( $args['list_id'] ) ),
		);

		$res = wp_remote_request(
			$url,
			array(
				'method'  => 'POST',
				'headers' => array(
					'api-key'      => $this->api_key,
					'Content-Type' => 'application/json',
				),
				'body'    => wp_json_encode( $body ),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $res ) ) {
			return array(
				'success' => false,
				'message' => $res->get_error_message(),
			);
		}
		$code = wp_remote_retrieve_response_code( $res );
		$json = json_decode( wp_remote_retrieve_body( $res ), true ) ?? array();

		if ( $code >= 200 && $code < 300 ) {
			return array_merge(
				$json,
				array(
					'success' => true,
				)
			);
		}
		return array_merge(
			$json,
			array(
				'success' => false,
			)
		);
	}

	public function get_region( $api_key ) {
		if ( strpos( $api_key, '-' ) === false ) {
			return null;
		}

		if ( empty( explode( '-', $api_key )[1] ) ) {
			return null;
		}

		return explode( '-', $api_key )[1];
	}
}
