<?php namespace Intellex\MailChimp\Api;

use Intellex\Curly\Method;
use Intellex\MailChimp\Enum\MergeFields;
use Intellex\MailChimp\Enum\SubscriberStatus;
use Intellex\MailChimp\Exception\ValidationException;
use Intellex\MailChimp\Exception\ExceptionFactory;
use Intellex\MailChimp\Resource\ResourceSubscriber;

/**
 * Class Subscriber
 * Handles all member (subscriber) API operations.
 *
 * @package Intellex\MailChimp\Api
 */
class ApiSubscribers extends ApiAbstract {

	/**
	 * Check if an email exists in the list.
	 *
	 * @param string $listId The unique ID of the list.
	 * @param string $email  The email to check.
	 *
	 * @return ResourceSubscriber|null The added member, or null if member not found.
	 */
	public function get($listId, $email) {
		$curl = $this->curl([ 'lists', $listId, 'members', md5($email) ]);

		if ($curl->getCode() !== 404) {
			return new ResourceSubscriber($curl->getContent());
		}

		return null;
	}

	/**
	 * Search subscribers
	 *
	 * @param string $listId The unique ID of the list.
	 *
	 * @return string All members maching the query. returns all members from the account or members from particular list.
	 */
	public function getAllFromList($listId) {

		return $this->curl('search-members?query=@&list_id=0d14093119', [], Method::GET)->getContent();;

	}

	/** Manage subscribers
	 *
	 * @param string $status    'subscribed', 'unsubscribed', 'cleaned', 'pending' (use pending to send a confirmation email).
	 * @param string $listId    The unique ID of the list.
	 * @param string $email     The email to add.
	 * @param string $firstName The first name of the user.
	 * @param string $lastName  The last name of the user.
	 *
	 * @return ResourceSubscriber The added member.
	 * @throws \Exception|ValidationException
	 */
	public function manage($listId, $email, $status, $firstName = '', $lastName = '') {

		// Check if list exists
		$list = $this->client->lists()->get($listId);
		if (!$list) {
			throw ExceptionFactory($response->getContent['detail']);
		}

		// Make sure that member is not in the list already
		$subscriberID = null;

		try {
			$subscriber = $this->get($listId, $email);

		} catch (ValidationException $ex) {

			// 404 error is expected in some cases
			if ($ex->getCode() !== 404) {
				throw $ex;
			}
		}

		$mergeFields =  array_filter([
			MergeFields::FNAME => $firstName,
			MergeFields::LNAME => $lastName
		]);

		// Execute
		$subscribersResponse = $this->curl([ 'lists', $listId, 'members', $subscriber ? md5($email) : '' ], [
			'email_address' => $email,
			'status'        => $status,
			'merge_fields'  => (object)$mergeFields
		], $subscriber ? Method::PATCH : Method::POST);

		return new ResourceSubscriber($subscribersResponse->getContent());
	}
}
